-2

I don't really understand where in the code that makes the character bounce to the right side and not countinue.

    public void exercise1e() {
    PaintWindow pw = new PaintWindow();
    Random rand = new Random();
    ImageIcon image = new ImageIcon("C:/Users/char.jpg");
    int width = pw.getBackgroundWidth();
    int height = pw.getBackgroundHeight();
    int dx = -2;
    int dy = 0;
    int x = 250;
    int y = rand.nextInt(height-100);

    while(true) {
        pw.showImage(image, x, y);
        PaintWindow.pause(20);
        x += dx;
        y += dy;
        if(x<0) {
            dx = -dx;
            if (x>0) {
        }
    }
}
}
  • Which framework? AWT, Swing, FX? [This example](http://stackoverflow.com/questions/14432816/how-to-move-an-image-animation/14436331#14436331) might also help – MadProgrammer Oct 02 '13 at 00:30
  • Change its position to the left and then to the right when reached the desired position.... Repeat the process will cause the bounce effect. If you reduce the X value of the position it will move to the left, increasing the X value will move it to the right. Stop the left when X is 0 or less and start right there, stop right when X is Window Size if that is the limit and move to the left. – porfiriopartida Oct 02 '13 at 00:34
  • More examples [here](http://stackoverflow.com/q/9849950/230513). – trashgod Oct 02 '13 at 00:37

1 Answers1

0

If you reach a boundary then change the direction to the opposite, dx=-dx will cause that effect. Your condition should be applied if reach the left limit.. when x<=0 and also when reached the right limit x>=width

if(x<=0 || x>=width ) {
    dx = -dx;
}

Now reset the position of your image to x. Otherwise you are just increasing and decreasing that number. Something like: image.setLocation(x,y), I can't be sure since I don't know what you are using to render this.

There is a logical contradiction in your current if statements.

   if(x<0) {
        Only if x is less than 0 evaluate the next if...
        if (x>0) {
            If x is less than 0 but also is greater than 0, understand the universe.
        }
    }
porfiriopartida
  • 1,546
  • 9
  • 17