1
我想在我的2D遊戲中正確旋轉一把劍。我有一個劍形圖像文件,我希望在播放器的位置旋轉圖像。我嘗試過使用Graphics2D和AffineTransform,但問題在於玩家在不同的座標平面上移動,屏幕類和圖形使用JFrame上像素的文字位置。所以,我意識到我需要通過旋轉圖像本身來呈現劍,然後將其保存到像素數組中以供我的屏幕類渲染。但是,我不知道該怎麼做。這裏是我的屏幕渲染方法的代碼:旋轉BufferedImage並將其保存到像素陣列
public void render(double d, double yOffset2, BufferedImage image, int colour,
int mirrorDir, double scale, SpriteSheet sheet) {
d -= xOffset;
yOffset2 -= yOffset;
boolean mirrorX = (mirrorDir & BIT_MIRROR_X) > 0;
boolean mirrorY = (mirrorDir & BIT_MIRROR_Y) > 0;
double scaleMap = scale - 1;
for (int y = 0; y < image.getHeight(); y++) {
int ySheet = y;
if (mirrorY)
ySheet = image.getHeight() - 1 - y;
int yPixel = (int) (y + yOffset2 + (y * scaleMap) - ((scaleMap * 8)/2));
for (int x = 0; x < image.getWidth(); x++) {
int xPixel = (int) (x + d + (x * scaleMap) - ((scaleMap * 8)/2));
int xSheet = x;
if (mirrorX)
xSheet = image.getWidth() - 1 - x;
int col = (colour >> (sheet.pixels[xSheet + ySheet
* sheet.width])) & 255;
if (col < 255) {
for (int yScale = 0; yScale < scale; yScale++) {
if (yPixel + yScale < 0 || yPixel + yScale >= height)
continue;
for (int xScale = 0; xScale < scale; xScale++) {
if (x + d < 0 || x + d >= width)
continue;
pixels[(xPixel + xScale) + (yPixel + yScale)
* width] = col;
}
}
}
}
}
}
這裏是我可憐的嘗試從劍類調用渲染方法之一:
public void render(Screen screen) {
AffineTransform at = new AffineTransform();
at.rotate(1, image.getWidth()/2, image.getHeight()/2);
AffineTransformOp op = new AffineTransformOp(at,
AffineTransformOp.TYPE_BILINEAR);
image = op.filter(image, null);
screen.render(this.x, this.y, image, SwordColor, 1, 1.5, sheet);
hitBox.setLocation((int) this.x, (int) this.y);
for (Entity entity : level.getEntities()) {
if (entity instanceof Mob) {
if (hitBox.intersects(((Mob) entity).hitBox)) {
// ((Mob) entity).health--;
}
}
}
}
感謝您的幫助,您可以提供,請隨時告訴我是否有更好的方法來做到這一點。
它旋轉圖像,但如何將圖像的像素保存爲數組? – Wookiederk 2014-11-07 02:39:38
@Wookiederk:我已經詳細闡述過了。 – trashgod 2014-11-07 11:59:01