Created
January 10, 2017 22:28
-
-
Save danamuise/11f514b04cf0178fdc484b477638306d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
/* | |
This script controls generic non-player characters with NavAgent component that walk around the | |
envronment, visiting waypoints and avoiding collisions. | |
*/ | |
public class Generic_NonPlayer : MonoBehaviour { | |
private GameObject[] wayPoints; | |
private int wayPointIndex =0; | |
public GameObject player; | |
Animator anim; | |
NavMeshAgent agent; | |
public bool moving; | |
Vector3 direction; | |
public float idleWait; | |
// Use this for initialization | |
void Start () { | |
direction = player.GetComponent<Transform>().position + this.transform.position; | |
anim = GetComponent<Animator> (); | |
agent = GetComponent<NavMeshAgent> (); | |
//load all waypoints into array. | |
wayPoints = GameObject.FindGameObjectsWithTag ("waypoint"); | |
wayPointIndex = Random.Range (0, wayPoints.Length); | |
//start walking | |
if(moving) StartCoroutine(Walk(0)); | |
} | |
void ChangeWaypoint() | |
{ | |
//randomly assign new destination | |
int currentWaypoint = wayPointIndex; | |
while (currentWaypoint == wayPointIndex) { | |
wayPointIndex = Random.Range (0, wayPoints.Length); | |
} | |
//Debug.Log ("Change destination to " + wayPoints [wayPointIndex].name); | |
} | |
// Update is called once per frame | |
void Update () { | |
if (moving) CheckArrival (); | |
} | |
//Character will walk to next waypoint and wait for "wait" seconds | |
IEnumerator Walk(float wait) | |
{ | |
yield return new WaitForSeconds (wait); | |
//Debug.Log ("Walking to Destination: " + wayPoints [wayPointIndex].name); | |
anim.SetBool ("isWalking", true); | |
agent.SetDestination (wayPoints [wayPointIndex].transform.position); | |
moving = true; | |
} | |
void Idle() | |
{ | |
//Debug.Log ("Idle"); | |
anim.SetBool ("isWalking", false); | |
} | |
//when arriving at a waypoint, load the next one | |
void CheckArrival() | |
{ | |
if (Mathf.Round(transform.position.x) == Mathf.Round(wayPoints[wayPointIndex].GetComponent<Transform>().position.x) && Mathf.Round(transform.position.z) == Mathf.Round(wayPoints[wayPointIndex].GetComponent<Transform>().position.z)) | |
{ | |
//Debug.Log ("Arrived at " + wayPoints [wayPointIndex].name); | |
Idle (); | |
ChangeWaypoint (); | |
StartCoroutine(Walk(idleWait)); | |
return; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment