top of page

3. Random Movement

1. Code for Random Movement

Right-click on your enemy class on the main screen and select 'Open editor'.

gf5.PNG

The enemy character should always be moving, so start with move(1);

​

Next we will use an if statement to start the random movement.

gf6.PNG
gf7.PNG

This code generates 10 random numbers and if it is less than 1 then it will run the proceeding code.

 

If we don't do this, the character will turn too much or too little.

This code generates a random angle between 0 and 90.

 

The - 45 part is necessary otherwise the character will always move to the right. See the diagram below for an explanation:

greenfoot7png.png
greenfoot8.png

2. Bounce at World Edge

You may have noticed that the enemy objects can get 'stuck' in the corners or when they hit the edge of the world.

​

In the act() method, below the random movement code, add the code in the red box.

 

This code checks to see if the object is at the edge, and turns it around (180 degrees) if it is.

gf9.PNG

3. Compile and Run

compile.PNG

Click the Compile button at the top of the code editor.

​

Then you can go back to the main Greenfoot window and click Run to test if your enemy objects move.

Click on me if you've got an error that you're stuck with.

bottom of page