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

2015/12/14

Object Back and Forth

ironphoenix20 ironphoenix20

2015/12/14

#
How do I make an actor move back and forth across the world, rather than stop when it reaches the edge?
Sam17 Sam17

2015/12/14

#
Try this: public void act() { if(atWorldEdge()) { turn(180); } } public boolean atWorldEdge() { if(getX() < 10 || getX() > getWorld().getWidth() - 10) return true; if(getY() < 10 || getY() > getWorld().getHeight() - 10) return true; else return false; }* *I take no credit for the 'atWorldEdge' method, it was created by Micheal Kölling.
ironphoenix20 ironphoenix20

2015/12/14

#
When I do this, it works but the object turns upside down when going back? I want it to turn around but still face right side up. What do I do?
danpost danpost

2015/12/14

#
Add an int field to the class to control the direction of movement:
private int direction = 1;
Then, the act method could simply be coded with the following:
move(direction);
if (isAtEdge()) direction = -direction;
If you are having the actor move at a faster rate, just multiply 'direction' by that rate of speed in the 'move' command.
ironphoenix20 ironphoenix20

2015/12/14

#
Thanks. I'll try that
You need to login to post a reply.