This site requires JavaScript, please enable it in your browser!
Greenfoot back
Alexlife2002003
Alexlife2002003 wrote ...

2018/10/25

Help with moving object

Alexlife2002003 Alexlife2002003

2018/10/25

#
So i want to make an object move up and down on its own but i can only make it go down. how do i make it go back up
danpost danpost

2018/10/25

#
Alexlife2002003 wrote...
So i want to make an object move up and down on its own but i can only make it go down. how do i make it go back up
How are you making it go down?
Alexlife2002003 Alexlife2002003

2018/10/26

#
setLocation(getX(), getY()+1); I am using that and when i try to apply the same but with -1 it does not work
danpost danpost

2018/10/26

#
Alexlife2002003 wrote...
setLocation(getX(), getY()+1); I am using that and when i try to apply the same but with -1 it does not work
Well, with that it will go down and then using -1 it will go up. To allow it to change, you would make it a variable:
1
2
int speed = 1;
setLocation(getX(), getY()+speed);
Next, the value of the variable needs to be retained; so, line 1 needs to be put outside the method
1
2
3
4
5
6
int speed = 1;
 
public void act()
{
    setLocation(getX(), getY()+speed);
}
Finally, you will need to change its value (negate it) so that the direction is reversed. You need an if statement with the conditions you require for the actor to change directions. So, complete the following and add it after the setLocation line in the act method:
1
if (<< place conditions here >>) speed = -speed;
You should have two conditions (or sets of conditions, depending on what you want), one for changing from down to up and one for up to down.
Alexlife2002003 Alexlife2002003

2018/10/27

#
thankyou so much this really helped
Alexlife2002003 Alexlife2002003

2018/10/28

#
I have another question: if(getY() >getWorld().getHeight()-5) speed=-speed; setLocation(getX(), getY()+speed); that is my condition so when it reaches the bottom it goes back up but any suggestions on how to make it go back down when it reaches the top?
danpost danpost

2018/10/28

#
Alexlife2002003 wrote...
any suggestions on how to make it go back down when it reaches the top?
HINT: You want to reverse directions when the actor is near the bottom (which you have) OR near the top (which you don't have).
You need to login to post a reply.