74 lines
2.6 KiB
C#
74 lines
2.6 KiB
C#
#if UNITY_5_3_OR_NEWER
|
|
using UnityEngine;
|
|
|
|
namespace RoboidControl.Unity {
|
|
/// <summary>
|
|
/// The Unity representation of a Roboid Control motor
|
|
/// </summary>
|
|
public class Motor : Thing {
|
|
|
|
/// <summary>
|
|
/// The core motor
|
|
/// </summary>
|
|
public RoboidControl.Motor coreMotor => base.core as RoboidControl.Motor;
|
|
|
|
/// <summary>
|
|
/// Create the Unity representation of the motor
|
|
/// </summary>
|
|
/// <param name="coreMotor">The core motor</param>
|
|
/// <returns>The Unity representation of a motor</returns>
|
|
/// 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>();
|
|
motor.Init(coreMotor);
|
|
}
|
|
else {
|
|
// Default implementation
|
|
GameObject gameObj = new(coreMotor.name);
|
|
motor = gameObj.AddComponent<Motor>();
|
|
motor.Init(coreMotor);
|
|
|
|
Rigidbody rb = gameObj.AddComponent<Rigidbody>();
|
|
rb.isKinematic = true;
|
|
}
|
|
return motor;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The maximum rotation speed of the motor in rotations per second
|
|
/// </summary>
|
|
public float maxSpeed = 5;
|
|
|
|
/// <summary>
|
|
/// The actual rotation speed in rotations per second
|
|
/// </summary>
|
|
public float rotationSpeed { get; protected set; }
|
|
|
|
/// <summary>
|
|
/// Update the Unity state
|
|
/// </summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Handle the binary event containing the rotation speed
|
|
/// </summary>
|
|
protected override void HandleBinary() {
|
|
RoboidControl.Motor coreMotor = core as RoboidControl.Motor;
|
|
this.rotationSpeed = coreMotor.targetSpeed * maxSpeed;
|
|
}
|
|
|
|
}
|
|
}
|
|
#endif |