How do I move the object Square2 along the y-axis continually? What I mean is when it touches the top of the world, it goes down. Then, when it hits the bottom, it moves back up.
Thanks in advance!


1 2 3 4 5 6 7 8 9 10 11 12 13 | //add this variable 1st private int moving; //then in the constructor moving = 10 //add this to act() int groundLevel = getWorld().getHeight() - getImage().getHeight()/ 2 ; if (getY() == 5 ) moving = 10 ; if (getY == groundLevel) moving = 10 ; setLocation(getX(), getY() + moving); |
1 2 3 4 5 6 7 8 9 10 11 12 | // first declare the field(s) private int direction = 1 ; // then the act method public void act() { int buffer = getImage().getHeight() / 2 ; if (getY() < buffer || getY() > getWorld().getHeight() - buffer) { direction = -direction; } setLocation(getX(), getY() + direction * speed); // see note below } |