Enemy Movement
Introduction
This tutorial covers how to create enemy movement in a top down game. Enemies in games may follow a set pattern or may follow the player.
This tutorial creates an Enemy entity which uses the Top Down movement values, but is fully controlled by logic rather than a physical input device.
New Project Setup
This project tutorial assumes a Top Down Standard starting point (using the wizard), but the steps here can be used to add an Enemy entity to any project. We assume that the game already has levels.
Enemy Entity
We'll be creating a new Enemy entity for this tutorial. To do thsi:
Click the Quick Actions tab
Click the Add Entity button
Enter the name Enemy
Check AxisAlignedRectangle
Check Top-Down for the Input Movement Type
Leave the rest of the defaults and click OK
We will also change the color of the enemy rectangle to tell it apart from the player:
Expand the Enemy Object folder
Select AxisAlignedRectangleInstance
Select the Variables tab
Change Width to 16
Change Height to 16
Change Color to Red
Adding an Enemy to Level1
To add an enemy to Level1:
Expand the Screens folder, then expand Level1's Objects folder
Select the EnemyList
Click the Quick Actions tab
Modify the X and Y values for the new enemy so it is inside of the level boundaries by changing X to 160 and Y to -160
Setting the InputDevice
So far our Enemy instance is an entity with no behavior - it simply stays in the same spot when the game runs. First, we'll mark it as using Top-Down movement:
Select the Enemy entity
Click the Entity Input Movement tab
Set Input Movement Type to Top-Down
Set Input Device to None (Can Assign in Code)
Now our Enemy has the behavior of top-down movement, but it is not using an input device for movement. Custom input can be set by defining an input device class which inherits from FlatRedBall.Input.InputDeviceBase. To do this:
Open the project in Visual Studio
Create a new class called EnemyInput. Mine is in an Input folder.
The EnemyInput class needs to inhert from the FlatRedBall.Input.InputDeviceBase class which provides virtual methods to control how the input device behaves. Although the InputDeviceBase class offers many virtual methods, the only two that the top-down movement logic uses are:
GetDefault2DInputX
GetDefault2DInputY
We can override these to return values between -1 and 1. In this case we'll return constant values to test the functionality, as shown in the following code snippet.
Next we need to assign the EnemyInput on the Enemy. To do this:
Open the Entities/Enemy.cs file in Visual Studio
Modify the CustomInitialize as shown in the following snippet:
Now we can run the game and see the enemy move down to the right.
Last updated