Skip to content

Instantly share code, notes, and snippets.

@moon-goon
Created March 2, 2016 03:26
Show Gist options
  • Save moon-goon/c438ad53b775c26bd615 to your computer and use it in GitHub Desktop.
Save moon-goon/c438ad53b775c26bd615 to your computer and use it in GitHub Desktop.
using UnityEngine;
public class AI_StateMachine : MonoBehaviour {
public Transform[] target;
public GameObject player;
private int destPoint = 0;
NavMeshAgent agent;
private float distance = 0.0f;
private float sightRange = 15f;
private Renderer myColor;
public Light flashLight;
public enum EnemyState {
Patrol,
Chase,
}
EnemyState _state;
private void Look() {
distance = Vector3.Distance(player.transform.position, agent.transform.position);
RaycastHit hit;
if (Physics.Raycast(gameObject.transform.position, gameObject.transform.forward, out hit, sightRange) && hit.collider.CompareTag("Player")) {
//enemy.chaseTarget = hit.transform;
_state = EnemyState.Chase;
}
if (distance > 6.0f) {
_state = EnemyState.Patrol;
}
flashLight.range = hit.distance;
}
void Start () {
_state = EnemyState.Patrol;
agent = GetComponent<NavMeshAgent>();
player = GameObject.FindGameObjectWithTag("Player");
myColor = gameObject.GetComponent<Renderer>();
flashLight = gameObject.GetComponentInChildren<Light>();
// Disabling auto-braking allows for continuous movement between points
agent.autoBraking = false;
if(_state == EnemyState.Patrol) {
GotoNextPath();
}
}
void Update () {
Look();
switch (_state) {
case EnemyState.Patrol:
myColor.material.color = Color.green;
if (agent.remainingDistance < 0.5f)
GotoNextPath();
break;
case EnemyState.Chase:
myColor.material.color = Color.red;
agent.destination = player.transform.position;
break;
}
}
void GotoNextPath() {
// Returns if no points have been set up
if (target.Length == 0)
return;
// Set the agent to go to the currently selected destination.
agent.destination = target[destPoint].position;
// Choose the next point in the array as the destination,
// cycling to the start if necessary.
destPoint = (destPoint + 1) % target.Length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment