I am very new to greenfoot. I want to make a ball bounce up and down repeatedly when I hit the act button. I have the code to get the ball to bounce down. However, I need the code to get it to bounce up. Can anyone help me out?


1 2 3 | else { speed = 0 ; } |
1 2 3 4 5 | else { speed = -speed; setLocation(getX(), ( int )(getY() + speed)); speed += 0.1 ; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public class Ball extends Actor { // Ball placed at bounce-point with speed consistant with that after bounce private double speed = - 9.0 ; public void act() { int myMaxY = getWorld().getHeight() - getImage().getHeight() / 2 ; int myNewY = getY() + ( int ) speed; // Check to see if edge of world will be reached on next move // I used the world's edge here, but it could be changed to bounce on an object instead (like the Ground) if ( myNewY > myMaxY) { // Adjust the value for the new location of ball after the bounce myNewY = 2 * myMaxY - myNewY; // Set ball's location at bounce-point setLocation(getX(), myMaxY); // Display ball bouncing getWorld().repaint(); // Set ball's location at new point after bounce setLocation(getX(), myNewY); // Apply bounce (-) and gravity (0.1) to speed speed = 0.1 - speed; } else { // Move ball to new location setLocation(getX(), myNewY); // Apply gravity (0.1) to speed speed += 0.1 ; } } } |