-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMoveRandom.cs
57 lines (42 loc) · 1.42 KB
/
MoveRandom.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
using UnityEngine;
using System.Collections;
public class MoveRandom : MonoBehaviour {
[Tooltip("Speed at which the object will move.")]
public float speed;
[Tooltip("Time interval between changing directions.")]
public float timeInterval;
[Tooltip("Minimum Y-value for motion.")]
public float floor;
[Tooltip("Maximum Y-value for motion.")]
public float ceiling;
private bool isMoving;
private Vector3 randomDirection;
private float nextUpdateTime;
// Use this for initialization
void Start () {
isMoving = false;
randomDirection = Random.insideUnitSphere;
nextUpdateTime = 0;
}
// Update is called once per frame
void Update () {
if (isMoving) {
transform.position += randomDirection * Time.deltaTime * speed;
if (Time.time >= nextUpdateTime) {
randomDirection = Random.insideUnitSphere;
// Check ceiling
if (this.transform.position.y + randomDirection.y * timeInterval * speed > ceiling && randomDirection.y > 0) {
randomDirection = new Vector3 (randomDirection.x, -randomDirection.y, randomDirection.z).normalized;
}
// Check floor
if (this.transform.position.y + randomDirection.y * timeInterval * speed < floor && randomDirection.y < 0) {
randomDirection = new Vector3 (randomDirection.x, -randomDirection.y, randomDirection.z).normalized;
}
nextUpdateTime = Time.time + timeInterval;
}
}
}
public void ToggleRandomMovement() {
isMoving = !isMoving;
}
}