#if UNITY_5_3_OR_NEWER
using Unity.VisualScripting;
using UnityEngine;
namespace RoboidControl.Unity {
///
/// The Unity representation of the TouchSensor
///
public class TouchSensor : Thing {
public SiteServer participant;
///
/// The core touch sensor
///
public RoboidControl.TouchSensor coreSensor {
get => (RoboidControl.TouchSensor)base.core;
}
///
/// Start the Unity represention
///
protected virtual void Start() {
if (core == null) {
participant = FindAnyObjectByType();
SetCoreThing(new RoboidControl.TouchSensor(participant.site));
}
// Somehow this does not work.
// Rigidbody rb = GetComponentInParent();
// if (rb == null) {
// RoboidControl.Thing thing = core;
// while (thing.parent != null)
// thing = thing.parent;
// Thing unityThing = thing.component;
// rb = unityThing.gameObject.AddComponent();
// rb.isKinematic = true;
// }
}
///
/// Create the Unity representation
///
/// The core touch sensor
/// The Unity representation of the touch sensor
public static TouchSensor Create(RoboidControl.TouchSensor core) {
GameObject gameObj = core.name != null ?
new(core.name) :
new("Touch Sensor");
TouchSensor component = gameObj.AddComponent();
Rigidbody rb = gameObj.AddComponent();
rb.isKinematic = true;
SphereCollider collider = gameObj.AddComponent();
collider.radius = 0.01f;
collider.isTrigger = true;
component.core = core;
component.participant = FindAnyObjectByType();
core.thisParticipant = component.participant.site;
if (core.parent != null && core.parent.component != null) {
gameObj.transform.SetParent(core.parent.component.transform, false);
}
if (core.position != null)
gameObj.transform.localPosition = core.position.ToVector3();
if (gameObj.transform.parent != null && gameObj.transform.localPosition.magnitude > 0) {
collider.radius = Vector3.Distance(gameObj.transform.position, gameObj.transform.parent.position) / 2;
gameObj.transform.position = (gameObj.transform.position + gameObj.transform.parent.position) / 2;
}
return component;
}
private void OnTriggerEnter(Collider other) {
if (other.isTrigger)
return;
if (this.transform.root == other.transform.root)
return;
this.coreSensor.touchedSomething = true;
}
private void OnTriggerExit(Collider other) {
if (other.isTrigger)
return;
this.coreSensor.touchedSomething = false;
}
}
}
#endif