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

2016/6/11

Moving randomly in four directions?

JamesHughes244 JamesHughes244

2016/6/11

#
Hey, I want my wombat to move randomly, left, right, up and down, but i dont want it to turn. How would I do this? I guess i would use:
if(Greenfoot.isKeyDown("right")) setLocation(getX()+3, getY());

if(Greenfoot.isKeyDown("left")) setLocation(getX()-3, getY());

if(Greenfoot.isKeyDown("down")) setLocation(getX(), getY()+3);

if(Greenfoot.isKeyDown("up")) setLocation(getX(), getY()-3);
but how would i randomly alternate between these four movements?
danpost danpost

2016/6/11

#
Well, there are four possible directions and one starting point (getX(), getY()). So,
int x = getX();
int y = getY();
int direction = Greenfoot.getRandomNumber(4);
Now, change 'x' and 'y' depending on the random direction:
if (direction == 0) x += 3;
if (direction == 1) y += 3;
if (direction == 2) x -= 3;
if (direction == 3) y -= 3;
and finally set the new location:
setLocation(x, y);
Unfortunately, the behavior (although it is what you asked for) will probably not be very pleasing as the average of the moves will end up at the current location of the actor (or, rather, the actor will tend to remain near the same location in the world).
JamesHughes244 JamesHughes244

2016/6/11

#
Thank you very much, this solution is great! The actor doesnt seem to stay near the same location in reality though so it works fine. Thanks again!
You need to login to post a reply.