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'.


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

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


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:


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.


3. Compile and Run


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