我正在尝试创建一个塔防风格的游戏,其目的是阻止攻击部队到达他们的目标。这是通过建造塔来完成的,塔可以用不同类型的攻击攻击敌人的波浪。由于我是编程新手,因此我希望在创建子弹的 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);
}