-
Notifications
You must be signed in to change notification settings - Fork 2
/
NinjaHook.cs
88 lines (67 loc) · 2.96 KB
/
NinjaHook.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
using UnityEngine;
using System.Collections;
public class NinjaHook: MonoBehaviour {
public Vector3 direction;
public float speed;
private bool isHooked_ = false;
public delegate void HookAction();
public event HookAction onHooked;
private Rigidbody2D rigidbody_;
protected void Start() {
this.initRigidbody_();
// Normalize direction and adapt hook angle
this.direction.Normalize();
gameObject.transform.eulerAngles = new Vector3(0f, 0f, NinjaHook.pointsToAngle(Vector3.zero, this.direction));
}
protected void FixedUpdate() {
// When hooked, the hook stops moving
if (this.isHooked_)
return ;
// Make sure the rotation is right (because of the parent)...
gameObject.transform.eulerAngles = new Vector3(0f, 0f, NinjaHook.pointsToAngle(Vector3.zero, this.direction));
// ... and also make sure the velocity hasn't changed
this.rigidbody_.velocity = this.direction * this.speed;
}
// Initialization
private void initRigidbody_() {
this.rigidbody_ = gameObject.GetComponent<Rigidbody2D>();
if (!this.rigidbody_) {
this.rigidbody_ = gameObject.AddComponent<Rigidbody2D>();
// No mass, no gravity. The entity is entirely managed by script
this.rigidbody_.mass = 0f;
this.rigidbody_.gravityScale = 0f;
}
this.rigidbody_.interpolation = RigidbodyInterpolation2D.Interpolate;
this.rigidbody_.collisionDetectionMode = CollisionDetectionMode2D.Continuous;
this.rigidbody_.sleepMode = RigidbodySleepMode2D.StartAwake;
}
// !Initialization
// Listeners
protected void OnCollisionEnter2D(Collision2D c) {
// Make kinematic to ensure the hook won't move anymore
this.rigidbody_.isKinematic = true;
gameObject.transform.eulerAngles = new Vector3(0f, 0f, NinjaHook.pointsToAngle(Vector3.zero, this.direction));
this.isHooked_ = true;
if (null != this.onHooked)
this.onHooked();
}
protected void OnTriggerEnter2D(Collider2D c) {
// Make kinematic to ensure the hook won't move anymore
this.rigidbody_.isKinematic = true;
gameObject.transform.eulerAngles = new Vector3(0f, 0f, NinjaHook.pointsToAngle(Vector3.zero, this.direction));
this.isHooked_ = true;
if (null != this.onHooked)
this.onHooked();
}
// !Listeners
// Util
public bool isHooked() { return this.isHooked_; }
public void rotateTo(Vector3 pos) {
this.transform.eulerAngles = new Vector3(0f, 0f, 180f + NinjaHook.pointsToAngle(gameObject.transform.position, pos));
}
private static float pointsToAngle(Vector2 anc1, Vector2 anc2) {
// Returns the angle between both vectors; note that the angle is NOT between -180 and 180
return (Mathf.Atan2(anc2.y - anc1.y, anc2.x - anc1.x) * Mathf.Rad2Deg - 90f);
}
// !Util
}