创建一个;子弹“;类(Java/swing)
我试图创建一个塔防风格的游戏,目标是阻止攻击部队到达他们的目标。这是通过建造塔楼来实现的,塔楼用不同的攻击方式攻击敌人的浪潮。由于我是编程新手,我希望能在创建bullet的挫折定位方法方面得到一些帮助 我一直试图复制:,但我无法使子弹顺利地移动到目标位置创建一个;子弹“;类(Java/swing),java,swing,class,projectile,Java,Swing,Class,Projectile,我试图创建一个塔防风格的游戏,目标是阻止攻击部队到达他们的目标。这是通过建造塔楼来实现的,塔楼用不同的攻击方式攻击敌人的浪潮。由于我是编程新手,我希望能在创建bullet的挫折定位方法方面得到一些帮助 我一直试图复制:,但我无法使子弹顺利地移动到目标位置 public class Bullets extends JComponent{ //x,y = the towers coordinates, where the shoot initiliazes from. //tx, ty = Targ
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 trig函数都采用弧度作为角度参数,而不是度。尝试Math.PI/2而不是90英寸: 双xDirection=5*Math.cos(-(Math.atan2(tx-x,tx-y))+90 双y方向=5*Math.sin(-(Math.atan2(tx-x,tx-y))+90
所有Java math trig函数都采用弧度作为角度参数,而不是度。尝试Math.PI/2而不是90英寸: 双xDirection=5*Math.cos(-(Math.atan2(tx-x,tx-y))+90 双y方向=5*Math.sin(-(Math.atan2(tx-x,tx-y))+90
我注意到在计算位移时有错误 片段:
Math.atan2(tx - x, tx - y))
你不是说
Math.atan2(tx - x, ty - y))
我注意到在计算位移时有错误 片段:
Math.atan2(tx - x, tx - y))
你不是说
Math.atan2(tx - x, ty - y))
无论您的计算结果如何,您的paintComponent()似乎每次都在相同的位置和大小上绘制项目符号
将新的x和y值存储到成员变量中,并使用paintComponent中的值
另外-Java的trig函数使用弧度,而不是度数,因此使用pi/2将引用更新为90度。无论您如何计算,您的paintComponent()似乎每次都在相同的位置和大小上绘制项目符号
将新的x和y值存储到成员变量中,并使用paintComponent中的值
另外-Java的trig函数使用弧度,而不是度,因此使用pi/2将引用更新为90度。在代码中,用于移动子弹的500毫秒(或ns)在哪里?游戏中的所有对象都应该是GUI模型。您应该有一个JPanel用作画布。一个JPanel绘制所有游戏对象以创建一帧动画。在代码中,用于移动子弹的500毫秒(或ns)在哪里?游戏中的所有对象都应该是GUI模型。您应该有一个JPanel用作画布。一个JPanel绘制所有游戏对象以创建一帧动画。