-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMovingPlatform.cs
More file actions
77 lines (68 loc) · 2.15 KB
/
Copy pathMovingPlatform.cs
File metadata and controls
77 lines (68 loc) · 2.15 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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovingPlatform : MonoBehaviour
{
[SerializeField] float speed;
[SerializeField] float timeBetweenEachWayPoint;
[SerializeField] Transform pathHolder;
private Rigidbody _rigidbody;
private int wayPointIndex = 0;
private float currentTime = 0;
private Vector3[] wayPoints;
private CharacterController characterController;
private void Start()
{
_rigidbody = GetComponent<Rigidbody>();
wayPoints = new Vector3[pathHolder.childCount];
for (int i = 0; i < wayPoints.Length; i++)
{
wayPoints[i] = pathHolder.GetChild(i).position;
}
transform.position = wayPoints[0];
}
private void PatrolAround()
{
if (wayPoints.Length <= 1) return;
if (Vector3.Distance(_rigidbody.position, wayPoints[wayPointIndex]) < 0.5)
{
Vector3 direction = wayPoints[(wayPointIndex + 1) % wayPoints.Length] - wayPoints[wayPointIndex];
currentTime += Time.deltaTime;
}
if (currentTime > timeBetweenEachWayPoint)
{
currentTime = 0;
wayPointIndex = (wayPointIndex + 1) % (wayPoints.Length);
}
Vector3 currentPos = Vector3.MoveTowards(transform.position, wayPoints[wayPointIndex], speed * Time.deltaTime);
_rigidbody.MovePosition(currentPos);
}
private void FixedUpdate()
{
PatrolAround();
}
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
characterController = other.GetComponent<CharacterController>();
}
}
private void OnTriggerStay(Collider other)
{
if (other.tag == "Player")
characterController.Move(_rigidbody.velocity * Time.deltaTime * 0.35f);
}
private void OnDrawGizmos()
{
Vector3 startPosition = pathHolder.GetChild(0).position;
Vector3 previousPosition = startPosition;
foreach (Transform waypoint in pathHolder)
{
Gizmos.DrawSphere(waypoint.position, 0.3f);
Gizmos.DrawLine(previousPosition, waypoint.position);
previousPosition = waypoint.position;
}
Gizmos.DrawLine(previousPosition, startPosition);
}
}