【问题标题】:Creating a "bullet" class (Java/swing)创建一个“子弹”类(Java/swing)
【发布时间】:2013-07-02 13:17:46
【问题描述】:

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

【问题讨论】:

  • 你的代码中哪里是 500ms(或者是 ns)用于移动子弹?
  • 游戏中的所有对象都应该是 GUI 模型。您应该拥有一个用作画布的 JPanel。那一个 JPanel 绘制所有游戏对象以创建一帧动画。

标签: java swing class projectile


【解决方案1】:

所有 Java 数学三角函数都采用弧度作为角度参数,而不是度数。试试 Math.PI/2 而不是 90 in:

double xDirection = 5* Math.cos(-(Math.atan2(tx - x, tx - y))+ 90);

双 yDirection = 5* Math.sin(-(Math.atan2(tx - x, tx - y))+ 90);

【讨论】:

    【解决方案2】:

    我注意到计算位移有错误

    片段:

    Math.atan2(tx - x, tx - y))
    

    你不是说吗?:

    Math.atan2(tx - x, ty - y))
    

    【讨论】:

      【解决方案3】:

      无论您的计算如何,您的 paintComponent() 似乎每次都在相同的位置和大小上绘制子弹。

      将新的 x 和新的 y 值存储到成员变量中并在 paintComponent 中使用。

      另外 - Java 的三角函数使用弧度,而不是度数,因此使用 pi / 2 将您的引用更新为 90 度。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-05
        • 1970-01-01
        • 1970-01-01
        • 2014-06-06
        • 2015-11-13
        • 1970-01-01
        相关资源
        最近更新 更多