Simple patrolling enemies in Unity

Let’s go over how to set up patrolling enemies for 2D platformer.

I have previously explained how to set up animation for 2D graphics in these two articles: one and two.

Create an empty game object and drag in the first sprite from the idle animation as a child of the game object. Reset the position on the sprite and make sure that the sprite is on the correct order layer:

Create the waypoints for the enemy to walk between by duplicating the game object and position. This is similar to what was done in earlier article for a moving platform. Remove all components from the waypoint objects:

Add a box collider to the parent object:

Create two scripts, one called Enemy, which will be the base class for all enemies and another called Skeleton, which is specific to this enemy type. Attach the Skeleton script to the parent object:

Open up the Enemy script and add:
-Float for the speed the enemy will move at
-Vector3 for the target to move to
-Vector3 for the current velocity of the enemy
-Vector3 for previous position in the last frame used for the velocity calculations
-Transform array for the waypoints
-Animator for the animator component on the graphics objects
-Bool to check if the enemy has flipped/rotated after reaching the waypoint

Initialise the animator and set the first waypoint to move to:

Create a coroutine for setting the next target. This is to ensure that the enemy waits before moving to the next waypoint. Create a function to turn the enemy towards the target:

Create the Movement function and call it from the Update function. Calculate the velocity of the enemy and pass it onto the animator. Without using the bool, the coroutine would constantly get called:

Add the waypoints to the script on the inspector:

Lastly, set up the animation state and transition:

Good luck!

--

--

--

Unity / C# Game developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

DevOps The AWS Way !!!

A Quick and Dirty Pytest Cookbook

Generating transcripts for an m3u8 video stream using google cloud speech to text

Five Reasons to run IBM Istio Helm chart for your service mesh

How to Use Verbs in Technical Writing

How to Setup Sonar Cube + Sonar Scanner with docker compose (Simple)

A Brief Guide to Using TinyDB

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Niklas Bergstrand

Niklas Bergstrand

Unity / C# Game developer

More from Medium

Bringing Agribusinesses On-chain

Journal - ABT Recap - 1–9–2022

KLAVYEDE KISA YOLLAR

DeHero Spring Carnival Begins! New Hero EX02 Debuts!