I have an image(“ball.gif”) that moves horizontally, the problem is how could I make the ball bounce when it reach the end of the size of the panel? I know this is not really difficult but I’m just a little bit confuse on how to do it.
Could someone help me about this matter?
This what I’ve tried so far :
public void paint(Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(ball, x, y, this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void cycle()
{
x += 1;
y += 0;
if (x >240)
{
x = 10;
y = 10;
}
}
public void run()
{
long beforeTime, elapsedTimeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (true)
{
cycle();
repaint();
elapsedTimeDiff = System.currentTimeMillis() - beforeTime;
sleep = DELAY - elapsedTimeDiff;
System.out.println(sleep);
if (sleep < 0)
{
sleep = 2;
}
try
{
Thread.sleep(sleep);
}
catch (InterruptedException e)
{
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
}
First, you need to hold your velocity in a field instead of hardcoding it:
Then when you do your bounds checking, flip your
xVelocity: