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

2014/9/2

Need help with small bit of code

pokemunn pokemunn

2014/9/2

#
Hi there, Would anyone be able to tell me how I would make an actor reverse its direction when it collides with another actor. I've just started using greenfoot and the most I know how to do is make the actor move in a single direction (right by default apparently). Thanks in advance. If you can provide code that would be very useful as I currently know very little of it.
Super_Hippo Super_Hippo

2014/9/2

#
setRotation(getRotation()+180);
//or just
turn(180);
Then the actor turns 180 degrees.
danpost danpost

2014/9/2

#
There are two Actor methods that can change the location of an actor in the world -- 'move(int)' and 'setLocation(int, int)'. With 'move(int)', you can use negative values for the 'int' to make the actor move backwards. As a possible alternative, you can use 'turn(180)'; but, note that the image of the actor will be upside down. With 'setLocation(int, int), you can "move" by 'dx' horizontally and by 'dy' vertically by using 'setLocation(getX()+dx, getY()+dy)'. Negative values will reposition left or up and positive values will reposition right or down.
pokemunn pokemunn

2014/9/2

#
Thanks guys, I ended up using a bit of code from a video tutorial in Mik's Blog. Where the actor detected when it was at the edge of the world (either left or right side) and then when that was true it turned 180. I originally planned to have two 'barriers' at either end which had the same image as the side of the background but this turned out to work just as well. Thanks again for your time. :)
You need to login to post a reply.