-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWalkingState.cs
90 lines (72 loc) · 2.46 KB
/
WalkingState.cs
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
using System;
using UnityEngine;
public class WalkingState : SmallEnemiesBaseState
{
[Header("Grid")]
[SerializeField] private Waypoint currentWaypoint;
[Header("Settings")]
[SerializeField] private float distanceTreshhold;
[SerializeField] private float movingSpeed;
private Vector2 _moveVelocity;
private Waypoint _lastWaypoint;
private Rigidbody2D _rb;
protected override void EnterState(SmallEnemiesStateMachine enemy)
{
_rb = enemy.Rigidbody;
InitialiseWaypoint();
}
protected override void ExitState(SmallEnemiesStateMachine enemy) { }
protected override void FixedUpdateState(SmallEnemiesStateMachine enemy)
{
GetDistanceToWaypoint(out var hasReachedWaypoint);
if (hasReachedWaypoint)
{
GetNewWaypoint();
MoveToWaypoint();
}
Debug.DrawLine(transform.position, currentWaypoint.transform.position);
}
private void InitialiseWaypoint()
{
if (currentWaypoint != null) return;
var hits = new Collider2D[2];
var hitCount = Physics2D.OverlapBoxNonAlloc(transform.position, transform.localScale, 0, hits);
for (int i = 0; i < hitCount; i++)
{
if (currentWaypoint != null) continue;
hits[i].TryGetComponent(out currentWaypoint);
_lastWaypoint = currentWaypoint;
}
MoveToWaypoint();
}
private void MoveToWaypoint()
{
var moveDirection = currentWaypoint.transform.position - transform.position;
_moveVelocity = moveDirection.normalized * (movingSpeed * Time.deltaTime);
_rb.velocity = _moveVelocity;
}
private float GetDistanceToWaypoint(out bool hasReachedWaypoint)
{
var distance = currentWaypoint.transform.position - transform.position;
hasReachedWaypoint = distance.magnitude <= distanceTreshhold;
return distance.magnitude;
}
private void GetNewWaypoint()
{
currentWaypoint.GetConnectedWaypoint(out var newWaypoint, out var isDeadEnd);
if (isDeadEnd)
{
currentWaypoint = _lastWaypoint;
}
else if (newWaypoint == _lastWaypoint)
{
GetNewWaypoint();
}
else
{
_lastWaypoint = currentWaypoint;
currentWaypoint = newWaypoint;
}
}
protected override void UpdateState(SmallEnemiesStateMachine enemy) { }
}