0

我正在尝试以初始水平速度模拟坠落的物体。我知道如何让它水平移动(无加速度),但由于方程 y = gt^2/2 + vt + y0,我很难让它垂直移动。由于二次方程,我遇到了问题。

我试图做的是做一个时间变量,每次由 SwingTimer 执行动作时,它就会增加一个。所以我实际上会有一个时间变量。但我认为这不是最好的方法吗?

有人可以将我推向正确的方向吗?

您可以在下面找到我已经编写的代码:

    public class Simulation extends JPanel implements ActionListener
    {
    Timer timer = new Timer(5,this);;
    private int Xpos=0, Ypos=0, velX, velY;
    private int Px,Py;

    JButton dropknop;
    private boolean drop = false;

    public Simulation()
    {
        this.setBackground(Color.white);
        velX = 2;
        velY = 2;

        dropknop = new JButton("DROP");
        dropknop.addActionListener(this);
        this.add(dropknop);
    }
    public int getXpos() {
        return Xpos;
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawRect(Xpos, 0, 20, 20);

        if(drop)
        {
            g.fillRect(Px, Py, 5, 5);
        }
    }

    public void actionPerformed(ActionEvent ae) 
    {
        if(ae.getSource() == dropknop)
        {
            Px = getXpos();
            this.drop = true;
        }
        if(Xpos<0 || Xpos>986)
        {
            velX = -velX;
        }
        if(Ypos<0 || Ypos>708)
        {
            velY = - velY;
        }

        if(drop)
        {
            Px += velY;
            Py += velX;
        }

        Ypos += velY;
        Xpos += velX;
        repaint();
    }
}

先感谢您!

4

1 回答 1

0

Gravity can be implemented by simply subtracting (assuming that the positive Y direction is up) a constant (the acceleration due to gravity) from the Y velocity in each frame.

The formula y = gt^2/2 + vt + y0 is for calculating the position after a specified time, but you're simulating it for every frame, so you need an incremental method:

velY = velY - gravity;

This yields an approximation of y = gt^2/2 + vt + y0 . How much it diverges depends on the time step. The reason for the difference is that this does not simulate the continuous acceleration between steps. (In theory, the result would be the same if the time step was infinitely small).

One way to make it more accurate (used by at least some physics engines) is to calculate multiple steps of this per frame (i.e. do a few iterations of the physics before updating the display).

For a scientifically accurate simulation, if no other forces are acting on the body, the method you suggest in the post is the most accurate.


In your actionPerformed method, you should probably be checking that the action is the timer event, before updating the positions (so that it doesn't move faster if another event occurs).

于 2013-04-21T14:49:44.210 回答