-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimple Waypoint Pathfinding with the Line of Sight AI
71 lines (66 loc) · 2.37 KB
/
Simple Waypoint Pathfinding with the Line of Sight AI
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WayPointAI : MonoBehaviour
{
public Transform player;
public Transform head;
Animator anim;
string state = "patrol";
public GameObject[] waypoints;
int currentWP = 0;
public float rotspeed = 0.2f;
public float speed = 1.5f;
public float accuracyWP = 5.0f;
void Start()
{
anim = GetComponent<Animator>();
}
void Update()
{
Vector3 direction = player.position - this.transform.position;
direction.y = 0;
float angle = Vector3.Angle(direction, head.up);
if (state == "patrol" && waypoints.Length > 0)
{
//anim.Play("walk");
print("Now walking");
if (Vector3.Distance(waypoints[currentWP].transform.position, transform.position) < accuracyWP)
{
//for random waypoint(next 3 line will be in comment section) -> //currentWP = Random.Range(0, waypoints.Length);
currentWP++;
if (currentWP >= waypoints.Length)
{
currentWP = 0;
}
}
//rotate towards waypoint
direction = waypoints[currentWP].transform.position - transform.position;
this.transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), rotspeed * Time.deltaTime);
this.transform.Translate(0, 0, Time.deltaTime * speed);
}
//angle from which AI will see the target
if(Vector3.Distance(player.position, this.transform.position)<10 && (angle<300 || state=="pursuing"))
{
state = "pursuing";
this.transform.rotation = Quaternion.Slerp(this.transform.rotation, Quaternion.LookRotation(direction), rotspeed * Time.deltaTime);
if(direction.magnitude > 5)
{
this.transform.Translate(0, 0, Time.deltaTime * speed);
//anim.Play("walk");
print("Now walking");
}
else
{
//anim.Play("attack");
print("Now attacking");
}
}
else
{
//anim.Play("walk");
print("Now walking");
state = "patrol";
}
}
}