Enemy AI patrols between points Script

Guard AI part 2

In this article we will make our guard move between waypoints.

Guard Patrol between Waypoints Pseudocode/logic

if waypoints exist .count > 0 && currenttarget != null

check distance between guard and destination
if the distance is less than 1 unit

if currenttarget == waypoints.count
turn on reverse
if currenttarget == 0
turn off reverse

if reverse is off increment currenttarget
if reverse is on then decrease currenttarget

set destination to current target

Guard Patrol between Waypoints Code

private NavMeshAgent _agent;
public List<Transform> waypoints;
private int currentTarget = 0;
private bool _isReverse = false;
void Start ()
{
_agent = GetComponent<NavMeshAgent>();
}

void Update ()
{
if (waypoints.Count > 0 && waypoints[currentTarget] != null)
{
float distance = Vector3.Distance(transform.position, waypoints[currentTarget].position);
if (distance < 1)
{
if (currentTarget >= waypoints.Count - 1)
{
_isReverse = true;
}
else if (currentTarget <= 0)
{
_isReverse = false;
}
if (_isReverse == true)
{
currentTarget--;
}
else if (_isReverse == false)
{
currentTarget++;
}
}
_agent.SetDestination(waypoints[currentTarget].position);
}
}

--

--

--

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

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

Recommended from Medium

Scaling to the rescue — Corrupted Azure App Services

Gesture Space

Ideal everyday life of a software engineer

Bamboo Deployment Tracking to Production Environments in Google Analytics

The difference between an AWS role and an instance profile

Development Update for June 14th, 2022

Chapter 4 — Encoding and Evolution

GrandQuest, venture into the unknown

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
Tristan Engel

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.

More from Medium

Unity Optimization Tools

Using a Service Worker to generate diagnostic XYZ tiles

Guidance of installing and usage of PostGIS on MacOS

The Maps API Handcuffs — and everyone is a victim