#if UNITY_5_3_OR_NEWER
using UnityEngine;
namespace RoboidControl.Unity {
///
/// The Unity representation of a Roboid Control motor
///
public class Motor : Thing {
///
/// The core motor
///
public RoboidControl.Motor coreMotor => base.core as RoboidControl.Motor;
///
/// Create the Unity representation of the motor
///
/// The core motor
/// The Unity representation of a motor
/// This uses a 'Motor' resource when available for the Unity representation.
/// If this is not available, a default representation is created.
public static Motor Create(RoboidControl.Motor coreMotor) {
Motor motor;
GameObject prefab = (GameObject)Resources.Load("Motor");
if (prefab != null) {
// Use resource prefab when available
GameObject gameObj = Instantiate(prefab);
motor = gameObj.GetComponent();
motor.Init(coreMotor);
}
else {
// Default implementation
GameObject gameObj = new(coreMotor.name);
motor = gameObj.AddComponent();
motor.Init(coreMotor);
Rigidbody rb = gameObj.AddComponent();
rb.isKinematic = true;
}
return motor;
}
///
/// The maximum rotation speed of the motor in rotations per second
///
public float maxSpeed = 5;
///
/// The actual rotation speed in rotations per second
///
public float rotationSpeed { get; protected set; }
///
/// Update the Unity state
///
protected override void FixedUpdate() {
base.FixedUpdate();
// We rotate the first child of the motor, which should be the axle.
float rotation = 360 * this.rotationSpeed * Time.fixedDeltaTime;
if (this.transform.childCount > 0)
this.transform.GetChild(0).Rotate(rotation, 0, 0);
}
///
/// Handle the binary event containing the rotation speed
///
protected override void HandleBinary() {
RoboidControl.Motor coreMotor = core as RoboidControl.Motor;
this.rotationSpeed = coreMotor.targetSpeed * maxSpeed;
}
}
}
#endif