Created
January 18, 2023 21:55
-
-
Save N-Carter/c9fb0546fb7d770fec226f1d03bc0f94 to your computer and use it in GitHub Desktop.
A self-levelling Rigidbody-based "vehicle" controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
[AddComponentMenu("Chassis/Hover Chassis")] | |
public class HoverChassis : Chassis | |
{ | |
[SerializeField] protected Transform m_CentreOfMass; | |
[SerializeField] protected Transform m_TurningForcePosition; | |
[SerializeField] protected Transform m_RaycastPoint; | |
[SerializeField] protected float m_SteerFactor = 1.0f; | |
[SerializeField] protected float m_DriveFactor = 1.0f; | |
[SerializeField] protected float m_HoverHeight = 1.0f; | |
[SerializeField] protected float m_LiftFactor = 1.0f; | |
[SerializeField] protected float m_SelfRightFactor = 1.0f; | |
[SerializeField] protected float m_TurnTiltFactor = 1.0f; | |
[SerializeField] protected float m_DriveLiftFactor = 0.2f; | |
protected float m_Altitude; | |
protected void Start() | |
{ | |
if(m_CentreOfMass) | |
m_Rigidbody.centerOfMass = m_CentreOfMass.transform.localPosition; | |
} | |
protected void FixedUpdate() | |
{ | |
if(!m_Takeoff) | |
return; | |
RaycastHit hit; | |
if(Physics.Raycast(m_RaycastPoint.position, -m_RaycastPoint.up, out hit)) | |
m_Altitude = hit.distance; | |
float steering = m_Steering * m_SteerFactor; | |
float drive = m_Drive * m_DriveFactor; | |
float lift = Mathf.Clamp((m_HoverHeight - m_Altitude) * m_LiftFactor, -m_LiftFactor, m_LiftFactor); | |
m_Rigidbody.AddRelativeForce(new Vector3(0.0f, lift + Mathf.Abs(drive), drive)); | |
m_Rigidbody.AddRelativeTorque(new Vector3(drive * m_DriveLiftFactor, steering * m_TurnTiltFactor, 0.0f)); | |
m_Rigidbody.AddForceAtPosition(transform.right * -steering, m_TurningForcePosition.position); | |
float offAngle = Vector3.Angle(transform.up, Vector3.up); | |
if(offAngle > 0.001f) | |
{ | |
Vector3 axis = Vector3.Cross(transform.up, Vector3.up); | |
m_Rigidbody.AddTorque(axis * offAngle * m_SelfRightFactor); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment