RoboidControl-csharp/Unity/DifferentialDrive.cs

73 lines
3.2 KiB
C#

#if UNITY_5_3_OR_NEWER
using System.Linq;
using UnityEngine;
namespace RoboidControl.Unity {
public class DifferentialDrive : Thing {
public WheelCollider leftWheel;
public WheelCollider rightWheel;
/// <summary>
/// Create the Unity representation
/// </summary>
/// <param name="core">The core touch sensor</param>
/// <returns>The Unity representation of the touch sensor</returns>
public static DifferentialDrive Create(RoboidControl.DifferentialDrive core) {
GameObject prefab = (GameObject)Resources.Load("DifferentialDrive");
if (prefab != null) {
// Use resource prefab when available
GameObject gameObj = Instantiate(prefab);
DifferentialDrive component = gameObj.GetComponent<DifferentialDrive>();
if (component != null)
component.core = core;
return component;
}
else {
// Fallback implementation
GameObject gameObj = new(core.name);
DifferentialDrive component = gameObj.AddComponent<DifferentialDrive>();
component.Init(core);
Rigidbody rb = gameObj.AddComponent<Rigidbody>();
rb.isKinematic = false;
rb.mass = 0.5f;
return component;
}
}
protected override void HandleBinary() {
RoboidControl.DifferentialDrive coreDrive = core as RoboidControl.DifferentialDrive;
if (leftWheel == null) {
GameObject leftWheelObj = new GameObject("Left wheel");
leftWheelObj.transform.SetParent(this.transform);
leftWheel = leftWheelObj.AddComponent<WheelCollider>();
leftWheel.mass = 0.1f;
leftWheel.suspensionDistance = 0.01f;
leftWheel.suspensionSpring = new JointSpring {
spring = 100f, // Very high spring value to make it rigid
damper = 10f, // Low damping (could be adjusted for slight 'bounciness')
targetPosition = 0.5f // Neutral position (middle of the suspension travel)
};
}
leftWheel.radius = coreDrive.wheelRadius;
leftWheel.center = new Vector3(-coreDrive.wheelSeparation / 2, 0, 0);
if (rightWheel == null) {
GameObject rightWheelObj = new GameObject("Right wheel");
rightWheelObj.transform.SetParent(this.transform);
rightWheel = rightWheelObj.AddComponent<WheelCollider>();
rightWheel.mass = 0.1f;
rightWheel.suspensionDistance = 0.01f;
rightWheel.suspensionSpring = new JointSpring {
spring = 100f, // Very high spring value to make it rigid
damper = 10f, // Low damping (could be adjusted for slight 'bounciness')
targetPosition = 0.5f // Neutral position (middle of the suspension travel)
};
}
rightWheel.radius = coreDrive.wheelRadius;
rightWheel.center = new Vector3(coreDrive.wheelSeparation / 2, 0, 0);
}
}
}
#endif