70 lines
2.6 KiB
C#
70 lines
2.6 KiB
C#
#if UNITY_5_3_OR_NEWER
|
|
using System.Collections;
|
|
using UnityEngine;
|
|
|
|
namespace RoboidControl.Unity {
|
|
|
|
/// <summary>
|
|
/// The Unity representation of a Roboid Control distance sensor
|
|
/// </summary>
|
|
public class DistanceSensor : Thing {
|
|
|
|
/// <summary>
|
|
/// The core distance sensor
|
|
/// </summary>
|
|
public RoboidControl.DistanceSensor coreSensor => base.core as RoboidControl.DistanceSensor;
|
|
|
|
/// <summary>
|
|
/// Start the Unity representation
|
|
/// </summary>
|
|
protected virtual void Start() {
|
|
StartCoroutine(MeasureDistance());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Create the Unity representation of the distance sensor
|
|
/// </summary>
|
|
/// <param name="core">The core distance sensor</param>
|
|
/// <returns>The Unity representation of the distance sensor</returns>
|
|
/// 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>();
|
|
distanceSensor.Init(coreSensor);
|
|
}
|
|
else {
|
|
// Default implementation
|
|
GameObject distanceObj = new(coreSensor.name);
|
|
distanceSensor = distanceObj.AddComponent<DistanceSensor>();
|
|
distanceSensor.Init(coreSensor);
|
|
}
|
|
return distanceSensor;
|
|
}
|
|
|
|
/// <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}");
|
|
coreSensor.distance = hitInfo.distance;
|
|
}
|
|
else
|
|
coreSensor.distance = 0;
|
|
}
|
|
yield return new WaitForSeconds(0.1f);
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
#endif |