- Walk until there is collision with a tile in front of him
- Short pause
- Turn around
- Walk in opposite direction until there is collision with a tile in front of him
- etc
First let's define our enemie's direction. Add a Create Event to the enemy object and write the following.
enemy_direction = 1;
We have now created enemy_direction and have given it the value 1. Now lets use it to make our enemy walk. Add a Step Event to the enemy object and use the enemy_direction as it's walking speed.
x += enemy_direction;
PATROLLING BEHAVIOUR
Next let's make the enemy stop, wait and turn around. For the wait we need a timer. We can create one in the Create Event.
wait_counter = 0;
We have now created wait_counter and set it to 0. We continue on the patrolling code by typing the following in the enemy's Step Event.
if enemy_direction = 1
{
if !(place_free(x+1,y))
{
wait_counter += 1;
x = xprevious;
if wait_counter >= 30
{
enemy_direction = -1;
wait_counter = 0;
}
}
}
That's quite a bit of code in one go, and we're not even done yet. Let's go through what we just coded. First we check if the enemy_direction is 1 (to the right). As we have created our enemy_direction with value 1 in the Create Event, in the beginning this will always be true.
Next we check if there isn't any place free right in front of the enemy. If this is true (meaning there is a solid object in front of him) we add 1 to the wait_counter every frame and the enemies x position is changed to his last known x position. This means he has stopped moving.
Afterwards we check if the wait_counter has reached 30. If so, the enemy_direction changes to -1 and the wait_counter is reset to 0. (I run my game on 60 frames per second, meaning 30 frames = 0.5 seconds. You can change your framerate under the Settings tab in your Room)
So to recap: The enemy walks to the right, stops when he encounters a solid object in front of him, waits for 0.5 seconds and turns around. But we aren't finished yet. We haven't told the enemy what to do once he's turned around. Luckily it's not that hard anymore as we want him to do the exact same thing but in the opposite direction. So straight underneath the above code we write the following.
else
{
if !(place_free(x-1,y))
{
wait_counter +=1;
x = xprevious ;
if wait_counter >= 30
{
enemy_direction = 1;
wait_counter = 0;
}
}
}
This does the exact same as the previous piece of code except it checks whenever the direction is not 1 (else) and changes the direction to 1 after the counter has reached 0.5 seconds.
We now have patrolling enemies!
ASSIGNMENT: CHECK FOR GAPS, FASTER MOVEMENT, INCREASED WAIT TIME
Make sure that whenever the enemy encounters a gap in the ground, he also stops moving, waits and turns around. Also increase his movement speed by 3(without changing enemy_direction in the Create Event) and his wait time to 1.0 seconds.
Take a look at how I did it (including assignment answers) here.