#if UNITY_5_3_OR_NEWER using System.Collections; using UnityEngine; namespace RoboidControl.Unity { /// /// The Unity representation of a Roboid Control distance sensor /// public class DistanceSensor : Thing { /// /// The core distance sensor /// public RoboidControl.DistanceSensor coreSensor => base.core as RoboidControl.DistanceSensor; /// /// Start the Unity representation /// protected virtual void Start() { StartCoroutine(MeasureDistance()); } /// /// Create the Unity representation of the distance sensor /// /// The core distance sensor /// The Unity representation of the distance sensor /// This uses a 'DistanceSensor' resource when available for the Unity representation. /// If this is not available, a default representation is created. public static DistanceSensor Create(RoboidControl.DistanceSensor coreSensor) { DistanceSensor distanceSensor; GameObject prefab = (GameObject)Resources.Load("DistanceSensor"); if (prefab != null) { // Use resource prefab when available GameObject gameObj = Instantiate(prefab); distanceSensor = gameObj.GetComponent(); distanceSensor.Init(coreSensor); } else { // Default implementation GameObject distanceObj = new(coreSensor.name); distanceSensor = distanceObj.AddComponent(); distanceSensor.Init(coreSensor); } return distanceSensor; } /// /// 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}"); coreSensor.distance = hitInfo.distance; } else coreSensor.distance = 0; } yield return new WaitForSeconds(0.1f); } } } } #endif