Reputation: 553
I'm trying to animate an object to move back and forth between two boundaries. For instance, once the x coordinate of the object reaches 500 it moves in the opposite direction to 200 and then moves back again until it reaches 500 and so on. However, the rectangle will only move to 500 and then stop. Here is a simplified version of my code:
public class Test
{
public static class Game extends JComponent implements ActionListener
{
int width=100;
int height=100;
int x=300;
int y=200;
Timer timer;
public Game()
{
timer = new Timer(20,this);
timer.start();
}
public void paint(Graphics g)
{
g.drawRect(x,y,width,height);
g.setColor(Color.red);
g.fillRect(x,y,width,height);
}
public void actionPerformed(ActionEvent e)
{
if(x>100)
{
x+=5;
}
if(x>500)
{
x-=5;
}
repaint();
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Test");
frame.setPreferredSize(new Dimension(800,600));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Game());
frame.pack();
frame.setVisible(true);
}
}
Upvotes: 0
Views: 4303
Reputation: 1487
You have a small logic error in your code.
if(x>100)
{
x+=5;
}
if(x>500)
{
x-=5;
}
If x
is greater than 500 it is also greater than 100. Therefore, when it reaches 505 it will add 5 then subtract 5 each update. I suggest that you have a movingRight
variable that you change based on x
.
boolean movingRight = true; // start moving right
… // start of update method
if(movingRight)
{
x+=5;
}
else
{
x-=5;
}
if (x == 500) // turn around and go the other way
{
movingRight = false;
}
else if (x == 200) // turn around and go the other way
{
movingRight = true;
}
repaint();
Upvotes: 1
Reputation: 347204
Look at it this way, based on your logic, while x
is greater than 100
, add 5
, while it's greater than 500
subtract 5
...
So once it reaches more than 500
, it's both greater than 100
AND greater than 500
...so you're going to add and subtract 5
, meaning it won't go anywhere.
What you need is a base delta
value which describes the amount of change to apply. You would then flip this value based on your ranges...
public void actionPerformed(ActionEvent e) {
x += delta;
if (x > 500) {
delta *= -1;
x = 500;
} else if (x < 100) {
delta *= -1;
x = 100;
}
repaint();
}
You may also want to have a look at Performing Custom Painting (as overriding paint
isn't recommended and you should be calling super.paint
so as not to break the paint chain) and Initial Threads
Upvotes: 4