RoboidControl-csharp/Unity/TouchSensor.cs

75 lines
2.3 KiB
C#

#if UNITY_5_3_OR_NEWER
using UnityEngine;
namespace RoboidControl.Unity {
/// <summary>
/// The Unity representation of a Roboid Control touch sensor
/// </summary>
public class TouchSensor : Thing {
/// <summary>
/// The core touch sensor
/// </summary>
public RoboidControl.TouchSensor coreSensor => base.core as RoboidControl.TouchSensor;
/// <summary>
/// Create the Unity representation of the touch sensor
/// </summary>
/// <param name="coreSensor">The core touch sensor</param>
/// <returns>The Unity representation of the touch sensor</returns>
/// This uses a 'TouchSensor' resource when available for the Unity representation.
/// If this is not available, a default representation is created.
public static TouchSensor Create(RoboidControl.TouchSensor coreSensor) {
TouchSensor touchSensor;
GameObject prefab = (GameObject)Resources.Load("TouchSensor");
if (prefab != null) {
// Use resource prefab when available
GameObject gameObj = Instantiate(prefab);
touchSensor = gameObj.GetComponent<TouchSensor>();
touchSensor.Init(coreSensor);
}
else {
// Default implementation
GameObject gameObj = new(coreSensor.name);
touchSensor = gameObj.AddComponent<TouchSensor>();
touchSensor.Init(coreSensor);
Rigidbody rb = gameObj.AddComponent<Rigidbody>();
rb.isKinematic = true;
SphereCollider collider = gameObj.AddComponent<SphereCollider>();
collider.radius = 0.01f;
collider.isTrigger = true;
}
return touchSensor;
}
/// <summary>
/// Handle touch trigger collider enter event
/// </summary>
/// <param name="other">The collider which entered our trigger collider</param>
private void OnTriggerEnter(Collider other) {
// Don't detect trigger colliders
if (other.isTrigger)
return;
// Don't touch yourself
if (this.transform.root == other.transform.root)
return;
this.coreSensor.touchedSomething = true;
this.core.updateQueue.Enqueue(new RoboidControl.Thing.CoreEvent(BinaryMsg.Id));
}
/// <summary>
/// Handl touch trigger collider exit event
/// </summary>
/// <param name="other">The collider which exited our trigger collider </param>
private void OnTriggerExit(Collider other) {
if (other.isTrigger)
return;
this.coreSensor.touchedSomething = false;
}
}
}
#endif