67 lines
2.3 KiB
C#
67 lines
2.3 KiB
C#
#if UNITY_5_3_OR_NEWER
|
|
using System.Collections;
|
|
using UnityEngine;
|
|
|
|
namespace RoboidControl.Unity {
|
|
|
|
/// <summary>
|
|
/// The Unity representation of a distance sensor
|
|
/// </summary>
|
|
public class DistanceSensor : Thing {
|
|
|
|
/// <summary>
|
|
/// The core distance sensor
|
|
/// </summary>
|
|
public new RoboidControl.DistanceSensor core {
|
|
get => (RoboidControl.DistanceSensor)base.core;
|
|
set => base.core = value;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Start the Unity representation
|
|
/// </summary>
|
|
protected virtual void Start() {
|
|
if (core == null) {
|
|
SiteServer siteServer = FindAnyObjectByType<SiteServer>();
|
|
SetCoreThing(new RoboidControl.DistanceSensor(siteServer.site));
|
|
}
|
|
|
|
StartCoroutine(MeasureDistance());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create the Unity representation of the distance sensor
|
|
/// </summary>
|
|
/// <param name="parent">The parent of the core distance sensor</param>
|
|
/// <returns>The Unity representation of the distance sensor</returns>
|
|
public static DistanceSensor Create(RoboidControl.DistanceSensor core) {
|
|
GameObject distanceObj = new("Distance sensor");
|
|
DistanceSensor component = distanceObj.AddComponent<DistanceSensor>();
|
|
if (core.parent != null && core.parent.component != null)
|
|
distanceObj.transform.SetParent(core.parent.component.transform, false);
|
|
|
|
return component;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Periodically measure the distance
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
IEnumerator MeasureDistance() {
|
|
while (Application.isPlaying) {
|
|
if (Physics.Raycast(this.transform.position, this.transform.forward, out RaycastHit hitInfo, 2.0f)) {
|
|
Thing thing = hitInfo.transform.GetComponentInParent<Thing>();
|
|
if (thing == null) {
|
|
// Debug.Log($"collision {hitInfo.transform.name} {hitInfo.distance}");
|
|
core.distance = hitInfo.distance;
|
|
}
|
|
else
|
|
core.distance = 0;
|
|
}
|
|
yield return new WaitForSeconds(0.1f);
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
#endif |