/
Troll.cs
94 lines (85 loc) · 2.25 KB
/
Troll.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Troll : MonoBehaviour
{
private Rigidbody2D rb;
private float speed = 10;
// directions
// 0 - right
// 1 - up
// 2 - left
// 3 - down
private int direction = 0;
// Start is called before the first frame update
private void Start()
{
rb = GetComponent<Rigidbody2D>();
// gravity has no effect on Troll
rb.gravityScale = 0;
// prevent physics enginge to rotate Troll
rb.freezeRotation = true;
}
// Update is called once per physics update
private void FixedUpdate()
{
if (direction == 0)
{
// right
rb.MovePosition(rb.position + new Vector2(speed, 0) * Time.deltaTime);
}
else if (direction == 1)
{
// up
rb.MovePosition(rb.position + new Vector2(0, speed) * Time.deltaTime);
}
else if (direction == 2)
{
// left
rb.MovePosition(rb.position + new Vector2(-speed, 0) * Time.deltaTime);
}
else if (direction == 3)
{
// down
rb.MovePosition(rb.position + new Vector2(0, -speed) * Time.deltaTime);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
SelectDirection();
SnapToGrid();
}
private void OnCollisionStay2D(Collision2D collision)
{
SelectDirection();
SnapToGrid();
}
private void SelectDirection()
{
// select new direction, not same direction
int deltaDirection = Random.Range(1, 3); // 1, 2 or 3
direction += deltaDirection;
direction = direction % 4;
}
private void SnapToGrid()
{
if (direction == 0 || direction == 2)
{
// moving right or left
SnapToGridY();
}
else
{
// moving up or down
SnapToGridX();
}
}
private void SnapToGridX()
{
rb.position = new Vector2((float)System.Math.Round(rb.position.x), rb.position.y);
}
private void SnapToGridY()
{
rb.position = new Vector2(rb.position.x, (float)System.Math.Round(rb.position.y));
}
}