我试图创造一个塔防御风格的游戏,在那里的目标是阻止攻击部队到达他们的目标。这是通过建造塔楼来实现的,它以不同的攻击方式攻击敌人的波涛。由于我刚开始编程,我希望在创建我的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);
}
发布于 2013-07-02 13:28:25
所有的Java数学三角函数都采用弧度作为角度参数,而不是度。尝试Math.PI/2,而不是90,在:
双xDirection = 5* Math.cos(-(Math.atan2(tx,tx ))+ 90); 双yDirection = 5* Math.sin(-(Math.atan2(tx,tx ))+ 90);
发布于 2013-07-02 13:40:05
我注意到在计算位移时有错误
碎片:
Math.atan2(tx - x, tx - y))
你不是说吗?:
Math.atan2(tx - x, ty - y))
发布于 2013-07-02 13:41:23
您的paintComponent()似乎每次都在相同的位置和大小上绘制子弹,而不管您的计算如何。
将新的x和新y值存储到成员变量中,并在paintComponent中使用这些变量。
另外,Java的trig函数使用的是弧度,而不是度,所以用pi / 2将引用更新到90度。
https://stackoverflow.com/questions/17426686
复制相似问题