AI move between points in Unity 2D

Daniel Kirwan
3 min readSep 6, 2021

Objective: Move an enemy unit between two points in Unity

Above you can see how the enemy will behave. It will move on its own to a set point, then play it’s idle animation and then walk towards another set point.

This is some very simple enemy AI, I will show you how I did this below.

First, I have a C# script called MossGiant that is inheriting from Enemy. This means that any enemy I make will have the same attributes but have separate values. More on inheritance and abstract classes in another article. For today, let’s focus on the MossGiant.

Let’s start inside the Unity editor. On my MossGiant game object, I dragged the sprite object inside of it so that the sprite is the child.

On my sprite I have the animator component for the animations and I have separated out the scripts to the parent.

You can see in the screenshot that I have already attached the transforms for the set locations to stop at, the sprite renderer and animator components. What is interesting here is that pointA and pointB transforms are fields inside of the parent enemy class and not the MossGiant.

Because they are protected, the child classes are allowed access to the fields, otherwise other scripts cannot access the fields see above.

The variables that I needed inside of the MossGiant are below:

I will need access to the Sprite so that I can flip the sprite on the X-axis so that it faces the other way, and the animator so that the MossGiant can control which animation that it is using. The currentTarget variable will be very useful for moving the MossGiant between the two points.

The behaviour I wanted was for the MossGiant to walk between the two points, stop once it has reached a point, plat the idle animation and the move to the next point.

Let’s run through the first part of the if/else statement.

when the mossGiant position is equal to that of pointA -> then I set the currentTarget to equal pointB position and play the idle animation. I do the reverse in the else if statement. Outside the statement I am then moving the mossGiant towards the newly updated currentTarget variable.

Make sure that your movement code is inside the update method. I am calling the MossMovement method in Update.

I also have a method that handles the flipping of the sprite. This is also called in update.

That is it for the code.

Now to create the two points to move between. Go back into Unity and find your enemy. My preferred method is to duplicate the enemy and then move the duplicates to where I want them. I then remove all components and leave the transform. Once you have them set up, drag the points into the empty space in editor. Don’t forget to also drag in the spriteRenderer and the animator.

You can now press play and the enemy will now move between the two points.

--

--