我正在尝试创建一款塔防风格的游戏,其目标是阻止攻击部队到达目标。这是通过 build 塔楼来完成的,塔楼会用不同类型的攻击来攻击一波又一波的敌人。由于我是编程新手,我希望在创建子弹的 SetBulletLocation 方法方面获得一些帮助。
我一直在尝试复制:this example ,但我无法让我的子弹顺利地飞向目标位置
public class Bullets extends JComponent{
//x,y = the towers coordinates, where the shoot initiliazes from.
//tx, ty = Target's x and y coordinates.
private int x,y,tx,ty;
private Point objectP = new Point();
public Bullets(int x, int y, int tx, int ty)
this.x = x;
this.y = y;
this.tx = tx;
this.ty = ty;
setBounds(x,y,50,50);
//Create actionlistener to updateposition of the bullet (setLocation of component)
ActionListener animate = new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
setBulletLocation();
}
};
Timer t = new Timer(500,animate);
t.start();
}
public void setBulletLocation() {
objectP = this.getLocation();
double xDirection = 5* Math.cos(-(Math.atan2(tx - x, tx - y))+ 90);
double yDirection = 5* Math.sin(-(Math.atan2(tx - x, tx - y))+ 90);
System.out.println(xDirection + " , " + yDirection);
x = (objectP.x + (int) xDirection);
y = (objectP.y + (int) yDirection);
setLocation(x, y);
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillOval(0, 0, 50, 50);
}
最佳答案
所有 Java 数学三角函数都采用弧度作为角度参数,而不是度数。尝试使用 Math.PI/2 而不是 90:
double xDirection = 5* Math.cos(-(Math.atan2(tx - x, tx - y))+ 90);
double yDirection = 5* Math.sin(-(Math.atan2(tx - x, tx - y))+ 90);
关于java - 创建 "bullet"类(Java/swing),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17426686/