-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNPCMovement.cs
99 lines (87 loc) · 2.68 KB
/
NPCMovement.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
91
92
93
94
95
96
97
98
99
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NPCMovement : MonoBehaviour
{
public float speed = 1.5f;
private Rigidbody2D _rigidbody;
private Animator _animator;
public bool isWalking = false;
public bool isTalking;
public float walkTime = 1.5f;
private float walkCounter;
public float waitTime = 4.0f;
private float waitCounter;
private Vector2[] walkingDirections =
{
Vector2.up, Vector2.down, Vector2.left, Vector2.right
};
private int currentDirection;
public BoxCollider2D npcZone;
private DialogueManager dialogueManager;
// Start is called before the first frame update
void Start()
{
_rigidbody = GetComponent<Rigidbody2D>();
_animator = GetComponent<Animator>();
waitCounter = waitTime;
walkCounter = walkTime;
isTalking = false;
dialogueManager = FindObjectOfType<DialogueManager>();
}
// Update is called once per frame
void FixedUpdate()
{
if (isTalking)
{
isTalking = dialogueManager.dialogueActive;
StopWalking();
return;
}
if (isWalking)
{
if(this.transform.position.x < npcZone.bounds.min.x ||
this.transform.position.x > npcZone.bounds.max.x ||
this.transform.position.y < npcZone.bounds.min.y ||
this.transform.position.y > npcZone.bounds.max.y)
{
StopWalking();
}
_rigidbody.velocity = walkingDirections[currentDirection] * speed;
walkCounter -= Time.fixedDeltaTime;
if (walkCounter < 0)
{
StopWalking();
}
}
else
{
_rigidbody.velocity = Vector2.zero;
waitCounter -= Time.fixedDeltaTime;
if (waitCounter < 0)
{
StartWalking();
}
}
}
private void LateUpdate()
{
_animator.SetBool("Walking", isWalking);
_animator.SetFloat("Horizontal", walkingDirections[currentDirection].x);
_animator.SetFloat("Vertical", walkingDirections[currentDirection].y);
_animator.SetFloat("LastH", walkingDirections[currentDirection].x);
_animator.SetFloat("LastV", walkingDirections[currentDirection].y);
}
public void StartWalking()
{
currentDirection = Random.Range(0, walkingDirections.Length);
isWalking = true;
walkCounter = walkTime;
}
public void StopWalking()
{
isWalking = false;
waitCounter = waitTime;
_rigidbody.velocity = Vector2.zero;
}
}