So we have to make a ball bounce with the code given. Basically the translate method below is run every 1 second because of a timer method in the tester. Also the tester passes dx as 0 and dy as 1. Initially the ball moves down and I am trying to make it bounce back up once it reaches y = 100. I can't figure out why this code would not work because logically it makes sense to me...
public void translate(int dx, int dy) {
x += dx;
y += dy;
if(y >= 100){
dy = -1 * dy;
}
}
I run it with this code, the ball keeps moving down. y = y direction of the ball and x = x direction of the ball
Update: Thanks for the answers. So from what I am getting I need to add the if statements inside the method that calls the translate method. The code for the method calling translate is:
private void moveMyShape() {
Timer t = new Timer(DELAY, getActionListener());
t.start();
} //method
private ActionListener getActionListener() {
return new
ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
myMoveableShape.translate(0, 1);
myShape.repaint();
}
};
}
So how would I go about adding if statements in this method? Like how can I keep track of the y position of the ball so I can add the if statements above the translate method. By the way this actionListener code is in a different class. It is in a tester class.
2nd Update: Yes, I have a public static int getY() inside the myMoveableShape. In the tester I added this code:
public void actionPerformed(ActionEvent ae) {
if(MyMoveableShape.getY() > 100 || MyMoveableShape.getY() < 0){
myMoveableShape.translate(0,-1);
}
myMoveableShape.translate(0,1);
myShape.repaint();
But the ball just gets to y = 100 position and stops moving.