EnemyMovement.cs 1.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;


public class EnemyMovement : MonoBehaviour{

	// variables

	// public vars
	// these should be set in the editor for each enemy however the designers want
	// distance from player before the enemy starts running
	public float noticeDistance;
	// speed for when the enemy is out of range but it will still be making its way towards the player
	public float creepSpeed;
	// speed for when the enemy is chasing the player
	public float chaseSpeed;

	// private vars
	private GameObject player;
	private NavMeshAgent navMesh;
	private Transform child;
	// Start is called before the first frame update
	void Awake(){
		// this is the player
		player = GameObject.FindGameObjectWithTag("Player");
		// this is the built in AI script
		navMesh = transform.GetComponent<NavMeshAgent> (); 
		// this is the visuals of the enemy
        child = transform.GetComponentInChildren<Transform>(); 
    }

	// Update is called once per frame
	void Update(){
DESKTOP-C0N3136\david's avatar
DESKTOP-C0N3136\david committed
36
		
37
		// check if the player is within the notice range
DESKTOP-C0N3136\david's avatar
DESKTOP-C0N3136\david committed
38
		if (Vector3.Distance (transform.position, player.transform.position) <= noticeDistance) {
39
40
41
42
43
44
45
46
47
48
49
50
51
52
			// make the enemy chase the player
			navMesh.speed = chaseSpeed;
		} else {
			// make the enemy slowly creep up on the player (or set creepSpeed to 0 to make the enemy not move at all)
			navMesh.speed = creepSpeed;
		}
		// this will make the enemy face the player
        child.LookAt(player.transform);
		// rotate the y by 90 degrees and set the x and z to 0
		child.rotation = Quaternion.Euler(0, child.rotation.eulerAngles.y -90, 0); 
		// tells the AI to follow the player
		navMesh.SetDestination (player.transform.position);
	}
}