Skip to content

Instantly share code, notes, and snippets.

@danamuise
Created January 10, 2017 22:39
Show Gist options
  • Save danamuise/aac7e0d65e8a33fb8b3ecdfeda459423 to your computer and use it in GitHub Desktop.
Save danamuise/aac7e0d65e8a33fb8b3ecdfeda459423 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
/*
This script controls generic non-player characters that follow another character.
*/
public class Follow_NonPlayer : MonoBehaviour {
Animator anim;
NavMeshAgent agent;
//follow this
public GameObject target;
//how far away from the target
public int maxDistance;
public int minDistance;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
agent = GetComponent<NavMeshAgent> ();
//fixes spin on collision
GetComponent<Rigidbody> ().freezeRotation = true;
}
// Update is called once per frame
void Update () {
CheckTarget ();
}
//check status of target
void CheckTarget()
{
if (target.GetComponent<Generic_NonPlayer> ().moving) {
Chase (maxDistance);
}
else
Idle (minDistance);
}
void Chase(int distance)
{
//if target walks away, begin chase
if (Vector3.Distance (target.GetComponent<Transform> ().position, this.transform.position) > distance) {
agent.SetDestination (target.GetComponent<Transform> ().position);
anim.SetBool ("isWalking", true);
}
}
void Idle(int distance)
{
//if target is close, stop chasing
if (Vector3.Distance (target.GetComponent<Transform> ().position, this.transform.position) < distance) {
anim.SetBool ("isWalking", false);
agent.SetDestination (transform.position);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment