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

How to evaluate AI and machine learning solutions

Voicebot: Why You Need to Add it for Your Customer Service Now

Calling all Developers and Entrepreneurs: How AIOZ Network incentivizes and rewards creators

Artificial Intelligence: Treasure Map or Ethical Minefield for Venture Capital?

AIOZ Network team highlight: Interview with the CEO Erman Tjiputra

Drones with Artificial Intelligence will soon become a powerful tool — a new perspective

GUIDE: How to Create a (damn cool) Multi-Language Chatbot with Manychat

aiSim 3.0 builds on Vulkan Ray Tracing to validate automated driving

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

How integers are stored in memory using two’s complement ?

Reinforcement Learning and its Offline Applications

Impact of Next-generation Wi-Fi 6 Technology on Industrial IoT

Use your NAS to its Fullest Potential: Best Add-On Packages for Synology NAS