2025-02-24 12:54:25 +01:00

68 lines
2.2 KiB
C#

#if UNITY_5_3_OR_NEWER
using UnityEngine;
namespace Passer.RoboidControl.Unity {
/// <summary>
/// The representation of a Thing in Unity
/// </summary>
public class Thing : MonoBehaviour {
/// <summary>
/// The core C# thing
/// </summary>
[field: SerializeField]
public RoboidControl.Thing core { get; set; }
/// <summary>
/// Set the core C# thing
/// </summary>
protected void SetCoreThing(RoboidControl.Thing thing) {
core = thing;
core.component = this;
SiteServer siteServer = FindAnyObjectByType<SiteServer>();
if (siteServer == null) {
Debug.LogWarning("No site server found");
return;
}
siteServer.site.Add(thing);
}
public static Thing Create(RoboidControl.Thing core) {
Debug.Log("Creating new Unity thing");
GameObject gameObj = string.IsNullOrEmpty(core.name) ?
new("Thing") :
new(core.name);
Thing component = gameObj.AddComponent<Thing>();
component.core = core;
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();
return component;
}
/// <summary>
/// Update the Unity representation
/// </summary>
protected virtual void Update() {
if (core == null)
return;
if (core.linearVelocity != null) {
Vector3 direction = Quaternion.AngleAxis(core.linearVelocity.direction.horizontal, Vector3.up) * Vector3.forward;
this.transform.Translate(core.linearVelocity.distance * Time.deltaTime * direction);
}
if (core.angularVelocity != null) {
Vector3 angularVelocity = core.angularVelocity.ToVector3();
this.transform.rotation *= Quaternion.Euler(angularVelocity * Time.deltaTime);
}
}
}
}
#endif