编辑:问题已解决。我忘了把 Math.toRadians() 放在我做 Math.cos 或 Math.sin 的任何地方。 :)
我正在开发一款简单的 Java 2D 游戏,其中包含两辆发射导弹并在屏幕上移动的坦克。 对于这个问题,我们假设只有一个坦克。
控制:
- 逆时针调整移动角度:向左箭头键
- 顺时针调整移动角度:右箭头键
- 向前移动:向上箭头键
- 发射导弹:ENTER
同时按向左或向右旋转 Sprite 。
我尝试编写游戏代码,使导弹从“坦克桶”(标记为绿色的点)发射。然而,我编写的代码并没有实现这一点。
相反,当按下 ENTER 键时,导弹会出现在 Sprite 上或其周围的一个点中,这似乎是随机的。
(橙色点是坦克的原点:tank.getX(),tank.getY())。
如果不是因为坦克旋转的事实,编写这个代码不会有问题。每次用户旋转水箱时,绿点的位置都会发生变化。
我的代码有什么问题?此代码应使导弹从当前“枪管”所在的任何位置“射击”。正如我所说,不起作用。
这是在用户按下 ENTER 时运行的程序。
enterAction = new AbstractAction(){
public void actionPerformed(ActionEvent e){
double missileXposition, missileYposition;
double tankMiddleX,tankMiddleY;
double angle, radius;
tankMiddleX = tank1.getX() + (tank1.getWidth()/2);
tankMiddleY = tank1.getY() + (tank1.getHeight()/2);
angle = tank1.getAngle();
radius = tank1.getWidth()/2;
missileXposition = tankMiddleX + ( Math.cos(angle) * radius );
missileYposition = tankMiddleY + ( Math.sin(angle) * radius );
missiles1.add( new Missile( missileXposition, missileYposition , "red" , tank1.getAngle() , tank1) );
}
};
导弹
类:
public class Missile extends Entity {
public Missile(double x, double y, String type, double angle, Tank tank){
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.type = type;
this.angle = angle;
if(type.equals("red")) image = new ImageIcon(this.getClass().getResource("sprites/redrocket1.png")).getImage();
if(type.equals("blue")) image = new ImageIcon(this.getClass().getResource("sprites/bluerocket1.png")).getImage();
width = image.getWidth(null);
height = image.getHeight(null);
if(type.equals("blue")) dx = (-1) * ( 6 * Math.cos(Math.toRadians(tank.getAngle())) );
if(type.equals("red")) dx = 6 * Math.cos(Math.toRadians(tank.getAngle()));
if(type.equals("blue")) dy = (-1) * ( 6 * Math.sin(Math.toRadians(tank.getAngle()) ) );
if(type.equals("red")) dy = 6 * Math.sin(Math.toRadians(tank.getAngle()));
}
}
非常感谢
最佳答案
确定 Sprite 原点(橙色)和导弹起点(绿色)之间的距离 (d
) 以及 Sprite 上边缘与橙绿色线之间的角度 一个
。
现在您将导弹的起点设置为
tank1.getX()+Math.cos(d*Math.toRadians(a+tank1.getAngle()));
tank1.getY()+Math.sin(d*Math.toRadians(a+tank1.getAngle()));
我不知道是否100%正确,但我认为这是正确的方向。
关于Java 2D "tank"游戏 : Shooting 'missile' from rotated sprite doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20922525/