-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAStarPathNavigator.cs
More file actions
94 lines (88 loc) · 2.41 KB
/
AStarPathNavigator.cs
File metadata and controls
94 lines (88 loc) · 2.41 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using UnityEngine;
using System.Collections;
//Note this line, if it is left out, the script won't know that the class 'Path' exists and it will throw compiler errors
//This line should always be present at the top of scripts which use pathfinding
using Pathfinding;
[RequireComponent(typeof(Seeker))]
public class AStarPathNavigator : MonoBehaviour
{
//The point to move to
//point that is calculated by AI
public Vector3 targetPosition;
//the seeker
private Seeker seeker;
//the AI
private TestAI ai;
//The calculated path
public Path path;
//The AI's speed per second
public float speed;
//The max distance from the AI to a waypoint for it to continue to the next waypoint
public float nextWaypointDistance = 3;
//The waypoint we are currently moving towards
private int currentWaypoint = 0;
public void Start ()
{
seeker = GetComponent<Seeker> ();
ai = GetComponent<TestAI> ();
}
public void SetTarget (Vector3 t)
{
targetPosition = t;
}
public void SetSpeed (float s)
{
speed = s;
}
public void FindPath ()
{
StopCoroutine ("CoMove");
seeker.StartPath (transform.position, targetPosition, OnPathComplete);
}
public void StartMove ()
{
StartCoroutine ("CoMove");
}
public void StopMove ()
{
StopCoroutine ("CoMove");
}
IEnumerator CoMove ()
{
while (true) {
if (currentWaypoint < path.vectorPath.Count) {
//Vector3 lookPos = ScriptUtilities.Vector3Utils.Subtract (path.vectorPath [currentWaypoint], transform.position);
//lookPos = lookPos.normalized * speed;
transform.LookAt (path.vectorPath [currentWaypoint]);
transform.Translate ((Vector3.forward * speed) * Time.fixedDeltaTime);
if (Vector3.Distance (transform.position, path.vectorPath [currentWaypoint]) < nextWaypointDistance) {
currentWaypoint++;
}
} else {
ai.TargetMet ();
}
yield return new WaitForSeconds (0.05f);
}
}
public void OnPathComplete (Path p)
{
Debug.Log ("Yay, we got a path back. Did it have an error? " + p.error);
if (!p.error) {
path = p;
//Reset the waypoint counter
currentWaypoint = 0;
StartMove ();
}
}
public void FixedUpdate ()
{
if (path == null) {
//We have no path to move after yet
return;
}
if (currentWaypoint >= path.vectorPath.Count) {
//StopMove ();
return;
}
}
}