Created
October 22, 2016 11:41
-
-
Save ginomessmer/da3458ecdb1f3a64c8b18a12a90d1803 to your computer and use it in GitHub Desktop.
Player car controller for Unity3d supporting multiple axles.
This file contains 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; | |
using System.Collections.Generic; | |
public class CarController : MonoBehaviour | |
{ | |
public List<AxleInfo> AxleInfos; | |
public float MaxMotorTorque; | |
public float MaxSteeringAngle; | |
public Transform CenterOfMass; | |
void FixedUpdate() | |
{ | |
this.GetComponent<Rigidbody>().centerOfMass = CenterOfMass.localPosition; | |
float motor = MaxMotorTorque * Input.GetAxis("Vertical"); | |
float steering = MaxSteeringAngle * Input.GetAxis("Horizontal"); | |
foreach(var info in AxleInfos) | |
{ | |
if (info.IsSteering) | |
{ | |
if (info.InvertSteering) | |
steering *= -1; | |
info.LeftWheel.steerAngle = steering; | |
info.RightWheel.steerAngle = steering; | |
} | |
if (info.IsMotor) | |
{ | |
info.LeftWheel.motorTorque = motor; | |
info.RightWheel.motorTorque = motor; | |
} | |
ApplyLocalWheelPosition(info.LeftWheel, info.LeftWheelTransform); | |
ApplyLocalWheelPosition(info.RightWheel, info.RightWheelTransform); | |
} | |
} | |
void ApplyLocalWheelPosition(WheelCollider wheel, Transform t) | |
{ | |
Vector3 position; | |
Quaternion rotation; | |
wheel.GetWorldPose(out position, out rotation); | |
t.position = position; | |
t.rotation = rotation; | |
} | |
} | |
[System.Serializable] | |
public class AxleInfo | |
{ | |
public WheelCollider LeftWheel; | |
public WheelCollider RightWheel; | |
public Transform LeftWheelTransform; | |
public Transform RightWheelTransform; | |
public bool IsMotor; | |
public bool IsSteering; | |
public bool InvertSteering; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment