# Thread: Swing timer, falling object

1. Member
Join Date
Apr 2012
Posts
4
Rep Power
0

## 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:
Java 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();
}
}```
Thank you in advance!

2. ## Re: Swing timer, falling object

You actually want to see your object falling? If so for each time t you have to draw your object at location (xt, yt) where yt is that quadratic equation. You may have to scale 'g' to see a nice parabola.

kind regards,

Jos

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•