#if UNITY_5_3_OR_NEWER using System.Collections; using UnityEngine; namespace RoboidControl.Unity { /// /// The Unity representation of a distance sensor /// public class DistanceSensor : Thing { /// /// The core distance sensor /// public new RoboidControl.DistanceSensor core { get => (RoboidControl.DistanceSensor)base.core; set => base.core = value; } /// /// Start the Unity representation /// protected virtual void Start() { if (core == null) { SiteServer siteServer = FindAnyObjectByType(); SetCoreThing(new RoboidControl.DistanceSensor(siteServer.site)); } StartCoroutine(MeasureDistance()); } /// /// Create the Unity representation of the distance sensor /// /// The parent of the core distance sensor /// The Unity representation of the distance sensor public static DistanceSensor Create(RoboidControl.DistanceSensor core) { GameObject distanceObj = new("Distance sensor"); DistanceSensor component = distanceObj.AddComponent(); if (core.parent != null && core.parent.component != null) distanceObj.transform.SetParent(core.parent.component.transform, false); return component; } /// /// Periodically measure the distance /// /// IEnumerator MeasureDistance() { while (Application.isPlaying) { if (Physics.Raycast(this.transform.position, this.transform.forward, out RaycastHit hitInfo, 2.0f)) { Thing thing = hitInfo.transform.GetComponentInParent(); 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