BlueGit

blue-star ggj-2020

Files

ggj-2020 / Assets / GAME / Scripts / Connectable.cs

Connectable.cs

New modules, fancy effects
timfa Tim Falken · pushed by timfa · 6 years ago
be3de6c4 History
Connectable.cs 2.5 KiB Download Raw
1using System.Collections;
2using System.Collections.Generic;
3using UnityEngine;
4
5public class Connectable : Grabbable
6{
7 [SerializeField] private float connectRange = 0.15f;
8 [SerializeField] private Vector3 connectionOffset;
9 [SerializeField] private Vector3 rotationOffset;
10 [SerializeField] private Connector.ConnectorTypes ConnectorType;
11
12 public bool ConnectTest;
13
14 public Connector ConnectedConnector;
15
16 void Update()
17 {
18 if(ConnectTest)
19 {
20 ConnectTest = false;
21 TryConnect();
22 }
23 }
24
25 public virtual void Activate() { }
26
27 public virtual void OnConnect() { }
28 public virtual void OnDisconnect() { }
29
30 public override void Grab(ObjectGrabber grabber)
31 {
32 base.Grab(grabber);
33
34 if(ConnectedConnector != null)
35 {
36 ConnectedConnector.Disconnect(this);
37 OnDisconnect();
38 }
39 }
40
41 public override void Release(Vector3 velocity, Vector3 torque)
42 {
43 base.Release(velocity, torque);
44
45 TryConnect();
46 }
47
48 public void Eject()
49 {
50 if(ConnectedConnector != null)
51 {
52 ConnectedConnector = null;
53 UnfreezeRigidbody();
54
55 rigidbody.AddTorque(Random.insideUnitSphere * 10);
56 rigidbody.AddForce(Random.insideUnitSphere * 100);
57
58 OnDisconnect();
59 }
60 }
61
62 private void TryConnect()
63 {
64 Connector[] connectors = FindObjectsOfType<Connector>();
65 Connector found = null;
66 float dist = connectRange;
67
68 for (int i = 0; i < connectors.Length; i++)
69 {
70 float aDist = Vector3.Distance(transform.position, connectors[i].transform.position);
71
72 if (aDist < dist && connectors[i].Connected == null && connectors[i].ConnectorType == ConnectorType)
73 {
74 dist = aDist;
75 found = connectors[i];
76 }
77 }
78
79 if (found != null)
80 {
81 ConnectedConnector = found;
82 rigidbody.isKinematic = true;
83 found.Connect(this);
84
85 rigidbody.constraints = RigidbodyConstraints.FreezeAll;
86
87 Vector3 offset = (found.ConnectionPoint.right * connectionOffset.x) + (found.ConnectionPoint.up * connectionOffset.y) + (found.ConnectionPoint.forward * connectionOffset.z);
88
89 transform.position = found.ConnectionPoint.position + offset;
90 transform.rotation = found.ConnectionPoint.rotation;
91
92 transform.Rotate(rotationOffset);
93
94 OnConnect();
95 }
96 }
97}