Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Unity 2021 Cookbook

You're reading from   Unity 2021 Cookbook Over 140 recipes to take your Unity game development skills to the next level

Arrow left icon
Product type Paperback
Published in Sep 2021
Publisher Packt
ISBN-13 9781839217616
Length 816 pages
Edition 4th Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Shaun Ferns Shaun Ferns
Author Profile Icon Shaun Ferns
Shaun Ferns
Matt Smith Matt Smith
Author Profile Icon Matt Smith
Matt Smith
Arrow right icon
View More author details
Toc

Table of Contents (15) Chapters Close

1. Displaying Data with Core UI Elements 2. Responding to User Events for Interactive UIs FREE CHAPTER 3. Inventory and Advanced UIs 4. Playing and Manipulating Sounds 5. Creating 3D Objects, Terrains, Textures, and Materials 6. 2D Animation and Physics 7. Characters, Game Kits, and Starter Assets 8. Web Server Communication and Online Version Control 9. Controlling and Choosing Positions 10. Navigation Meshes and Agents 11. Cameras and Rendering Pipelines 12. Shader Graphs and Video Players 13. Advanced Topics - Gizmos, Automated Testing, and More 14. Particle Systems and Other Visual Effects 15. Virtual and Augmented Reality (VR/AR)

Constantly updating the NavMeshAgent's destination to flee from the player's current location

There are times when we want an AI-controlled NPC character to move away from another character, rather than go toward it. For example, an enemy with very low health might run away, and so gain time to regain its health before fighting again. Or, a wild animal might flee from any other character moving near it.

To instruct our NavMeshAgent component to flee from the player's location, we need to replace the ArrowNPCMovement C# script class with the following:

 using UnityEngine;
using UnityEngine.AI;

public class ArrowNPCMovement : MonoBehaviour {
public float runAwayDistance = 10;
public GameObject targetGO;
private NavMeshAgent navMeshAgent;

void Start() {
navMeshAgent = GetComponent<NavMeshAgent>();
}

void Update() {
Vector3 targetPosition = targetGO.transform.position;
float distanceToTarget = Vector3.Distance(transform.position, targetPosition);
if...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image