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

2016/10/10

Randomly turning left or right

brobeans77 brobeans77

2016/10/10

#
I know this is incredibly basic but I happened to be absent the day we covered how to randomly turn right or left
public class Worm extends Actor
{
    public void act()
    {
        checkKeypress();
        if ( isAtEdge())
        {
            turn(Greenfoot.getRandomNumber(19) - 18);
        }
    }
    public void checkKeypress()
    {
        if ( Greenfoot.isKeyDown("left") )
        {
            move(Greenfoot.getRandomNumber(4) - 6);
        }
    }
}
I need the worm to go left or right when its hits the edge of the world and right now he is only going right
danpost danpost

2016/10/10

#
brobeans77 wrote...
I need the worm to go left or right when its hits the edge of the world and right now he is only going right
Eighteen is the maximum number that can be gotten with 'Greenfoot.getRandomNumber(19)'. Therefore, if you subtract 18 from that your result will never be positive. This means that you would always turn left, not right. If you subtract '9' or get a random number using '37', you will turn in both directions (not at the same time, of course).
brobeans77 brobeans77

2016/10/11

#
thank you so much
You need to login to post a reply.