# Swing timer, falling object

• 04-21-2013, 06:24 PM
ICEpower
Swing timer, falling object
I'm trying to simulate a falling object with an initial horizontal speed. I understand how to make it move horizontally (no acceleration) but I have some trouble making it move vertically because of the equation y = gt^2/2 + vt + y0. I have problems because of the quadratic equation. I also want to plot the graph of the falling object.

What I tried to do is to do make a time variable which would increase by one every time the action is performed by the SwingTimer. So that I would actually have a timevariable. But I don't think that is the best way to do it?

Can somebody push me in the right direction?

Below you can find the code I have already written:
Code:

```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()     {         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();     } }```