【问题标题】:Java: Rotate Image around different pointsJava:围绕不同点旋转图像
【发布时间】:2013-02-16 17:04:19
【问题描述】:

我对编程很陌生,我正在尝试制作一个小游戏,您可以在其中独立控制(旋转)坦克和坦克顶部的不同枪支。 (我用的是光滑的)

在坦克旋转期间,火炮应围绕坦克图像的中心旋转,因为它们已连接。

public void drawTankandGuns(){
  tankImage.draw(position.x, position.y);
  gunImage.draw(position.x+canonOffsetX, position.y+canonOffsetY);
}

public void rotateDuringMovement(){
  gunImage.setCenterOfRotation(tankImage.getWidth/2-gunOffsetX,
    tankImage.getHeight/2-gunOffsetY);

  gunImage.rotate(angle);
  tankImage.rotate(angle);
}

到目前为止效果很好。枪连接并与坦克一起旋转。但是如果我想在没有坦克的情况下旋转枪(并且坦克已经旋转)并将旋转中心设置回枪,枪图像被拉回到其原始位置,失去了围绕坦克旋转的位置.. .

编辑:解决方案是使用不同的方法。绘制 gunImage 取决于 tankImage 旋转的 sin/cos。

【问题讨论】:

  • 如果您找到了问题的解决方案,请继续提交答案。您可以标记为答案。

标签: java rotation center point slick2d


【解决方案1】:

解决方案是使用不同的方法。 绘制 gunImage 取决于 tankImage 旋转的 sin/cos。

//calculate the gun position on top of the tank
gunPosX = tankPosX + gunPosOffsetX;
gunPosY = tankPosY + gunPosOffsetY;

//calculate the tank rotation center
tankRotationsCenterX = tankPosX + tankImage.getCenterOfRotationX();
tankRotationsCenterY = tankPosY + tankImage.getCenterOfRotationY();

//calculate distance between gun position and tank rotation center
dx = tankRotationsCenterX - gunPosX ;
dy = tankRotationsCenterY - gunPosY ;
dis = Math.sqrt(dx * dx + dy * dy);

//calculate the offset based on the rotation of the tank
//rotation offset for the gun placement
gunRotaOff = 20;

gunX_offset = dis*Math.cos(Math.toRadians(tankImage.getRotation()+gunRotaOff));
gunY_offset = dis*Math.sin(Math.toRadians(tankImage.getRotation()+gunRotaOff));

gunXhalf = gun.getImage().getWidth() / 2;
gunYhalf = gun.getImage().getHeight() / 2;

//draws the gun dependend on the ship position and the ship rotation
//don't forget to subtract half the width/height for exact positioning
gun.drawIngame(tankRotationsCenterX - gun_x_offset)-gunXhalf , (tankRotationsCenterY - gun_y_offset) - gunYhalf ));

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    相关资源
    最近更新 更多