Unity Car controller / AI car (JS 版本)
PlayerCar_Script (C#) :
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(AudioSource))]
public class PlayerCar_Script : MonoBehaviour {
// These variables allow the script to power the wheels of the car.
[SerializeField]
WheelCollider frontLeftWheel, frontRightWheel, backLeftWheel, backRightWheel;
/**
* These variables are for the gears, the array is the list of ratios. The script
uses the defined gear ratios to determine how much torque to apply to the wheels.
*/
[SerializeField]
float[] gearRatio;
[SerializeField]
float differentialRatio = 3.21f;
[SerializeField]
int currentGear = 0;
/**
* These variables are just for applying torque to the wheels and shifting gears.
using the defined Max and Min Engine RPM, the script can determine what gear the
car needs to be in.
*/
[SerializeField]
float engineTorque = 600f, maxEngineRPM = 700f, minEngineRPM = 1000f, engineRPM = 0f;
[SerializeField]
int frontWheelDrive = 1, rearWheelDrive = 1;
// Center Of Mass
[SerializeField]
float comX = 0f, comY = 0f, comZ = 0f;
private Rigidbody rigidbody;
private AudioSource audioSource;
// Use this for initialization
void Start () {
// I usually alter the center of mass to make the car more stable. I'ts less likely to flip this way.
rigidbody = GetComponent<Rigidbody>();
rigidbody.centerOfMass = new Vector3(comX, comY, comZ);
audioSource = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update () {
//update center of mass
rigidbody.centerOfMass = new Vector3(comX, comY, comZ);
/**
* This is to limith the maximum speed of the car, adjusting the drag probably isn't the best way of doing it,
but it's easy, and it doesn't interfere with the physics processing.
*/
rigidbody.drag = rigidbody.velocity.magnitude / 250;
// Compute the engine RPM based on the average RPM of the two wheels, then call the shift gear function
engineRPM = Mathf.Abs(backLeftWheel.rpm + backRightWheel.rpm) / 2 * gearRatio[currentGear] * differentialRatio;
if (engineRPM > 10000)
engineRPM = 10000;
if (engineRPM < 0)
engineRPM = 0;
shiftGears();
/**
* set the audio pitch to the percentage of RPM to the maximum RPM plus one, this makes the sound play
up to twice it's pitch, where it will suddenly drop when it switches gears.
*/
audioSource.pitch = Mathf.Abs(engineRPM / maxEngineRPM) + 0.5f;
if (audioSource.pitch > 1.5f)
audioSource.pitch = 1.5f;
/**
* finally, apply the values to the wheels. The torque applied is divided by the current gear, and
multiplied by the user input variable.
*/
if (frontWheelDrive.Equals(1)) {
frontLeftWheel.motorTorque = -engineTorque * gearRatio[currentGear] * differentialRatio * Input.GetAxis("Vertical");
frontRightWheel.motorTorque = -engineTorque * gearRatio[currentGear] * differentialRatio * Input.GetAxis("Vertical");
}
if (rearWheelDrive.Equals(1)) {
backLeftWheel.motorTorque = -engineTorque * gearRatio[currentGear] * differentialRatio * Input.GetAxis("Vertical");
backLeftWheel.motorTorque = -engineTorque * gearRatio[currentGear] * differentialRatio * Input.GetAxis("Vertical");
}
// the steer angle is an arbitrary value multiplied by the user input.
frontLeftWheel.steerAngle = 35 * Input.GetAxis("Horizontal");
frontRightWheel.steerAngle = 35 * Input.GetAxis("Horizontal");
}
void shiftGears()
{
/**
* this funciton shifts the gears of the vehcile, it loops through all the gears, checking which will make
the engine RPM fall within the desired range. The gear is then set to this "appropriate" value.
*/
if (engineRPM >= maxEngineRPM)
{
int appropriateGear = currentGear;
for (int i = 0; i < gearRatio.Length; i++)
{
if (Mathf.Abs(backLeftWheel.rpm + backRightWheel.rpm) / 2 * gearRatio[i] * differentialRatio < maxEngineRPM)
{
appropriateGear = i;
break;
}
}
currentGear = appropriateGear;
}
}
}
------------------------------------------------
WheelAntiRoll_Script(C#):
using UnityEngine;
using System.Collections;
public class WheelAntiRoll_Script : MonoBehaviour {
// Car two Wheel
[SerializeField]
WheelCollider wheelL, wheelR;
[SerializeField]
float AntiRoll = 5000.0f;
private Rigidbody rigidbody;
void Start() {
rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate() {
WheelHit hits;
bool groundedL = wheelL.GetGroundHit(out hits);
float travelL = 1.0f;
float travelR = 1.0f;
if (groundedL)
travelL = (-wheelL.transform.InverseTransformPoint(hits.point).y - wheelL.radius) / wheelL.suspensionDistance;
bool groundedR = wheelR.GetGroundHit(out hits);
if (groundedR)
travelR = (-wheelR.transform.InverseTransformPoint(hits.point).y - wheelR.radius) / wheelR.suspensionDistance;
float antiRollForce = (travelL - travelR) * AntiRoll;
if (groundedL)
rigidbody.AddForceAtPosition(wheelL.transform.up * - antiRollForce, wheelR.transform.position);
if (groundedR)
rigidbody.AddForceAtPosition(wheelR.transform.up * antiRollForce, wheelR.transform.position);
}
}
------------------------------------------------
WheelAlignment_Script (C#) :
using UnityEngine;
using System.Collections;
public class WheelAlignment_Script : MonoBehaviour {
[SerializeField]
WheelCollider correspondingCollider;
[SerializeField]
GameObject slipSmoke;
float rotationValue = 0f;
void FixedUpdate()
{
// define a hit point for the raycast collision
RaycastHit hits;
/**
* Find the collider's center point, you need to do this because the center of the collider might not actually be
the real position if the transform's off.
*/
Vector3 colliderCenterPoint = correspondingCollider.transform.TransformPoint(correspondingCollider.center);
/**
* now cast a ray out from the wheel collider's center the distance of the suspension, if it hit something, then use the "hit"
variable's data to find where the wheel hit, if it didn't, then se tthe wheel to be fully extended along the suspension.
*/
Vector3 hitsporit = (Physics.Raycast(colliderCenterPoint, -correspondingCollider.transform.up, out hits, correspondingCollider.suspensionDistance + correspondingCollider.radius)) ? hits.point + (correspondingCollider.transform.up * correspondingCollider.radius) : colliderCenterPoint - (correspondingCollider.transform.up * correspondingCollider.suspensionDistance);
transform.position = hitsporit;
/**
* now set the wheel rotation to the rotation of the collider combined with a new rotation value. This new value
is the rotation around the axle, and the rotation from steering input.
*/
transform.rotation = correspondingCollider.transform.rotation * Quaternion.Euler(rotationValue, correspondingCollider.steerAngle, 0);
// increase the rotation value by the rotation speed (in degrees per second)
rotationValue += correspondingCollider.rpm * (360 / 60) * Time.deltaTime;
/**
* define a wheelhit object, this stores all of the data from the wheel collider and will allow us to determine
the slip of the tire.
*/
WheelHit wheelhits;
correspondingCollider.GetGroundHit(out wheelhits);
/**
* if the slip of the tire is greater than 2.0, and the slip prefab exists, create an instance of it on the ground at
a zero rotation.
*/
if (Mathf.Abs(wheelhits.sidewaysSlip) > 2)
{
if (slipSmoke)
Instantiate(slipSmoke, wheelhits.point, Quaternion.identity);
}
}
}
------------------------------------------------
WheelFriction_Script (C#) :
using UnityEngine;
using System.Collections;
public class WheelFriction_Script : MonoBehaviour {
[SerializeField]
WheelCollider frontLeftWheel, frontRightWheel, backLeftWheel, backRightWheel;
// Wheel Friction curves
[SerializeField]
float forwardExtremumSlip = 10f, //1.0f
forwardExtremumValue = 100f, //20000.0f
forwardAsymptoteSlip = 100f, //2.0f
forwardAsymptoteValue = 1f, //10000.0f
forwardStiffness = 1.0f,
sidewaysExtremumSlip = 6f, //1.0f
sidewaysExtremumValue = 100f, //20000.0f
sidewaysAsymptoteSlip = 30f, //2.0f
sidewaysAsymptoteValue = 1, //1000f
sidewaysStiffness = 2.0f;
WheelFrictionCurve frontLeftWheelFrictionCurve, frontRightWheelFrictionCurv, backLeftWheelFrictionCurv, backRightWheelFrictionCurv;
Rigidbody rigidbody;
void Start() {
frontLeftWheelFrictionCurve = frontLeftWheel.forwardFriction;
frontRightWheelFrictionCurv = frontRightWheel.forwardFriction;
backLeftWheelFrictionCurv = backLeftWheel.forwardFriction;
backRightWheelFrictionCurv = backRightWheel.forwardFriction;
rigidbody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update () {
// Forward Friction
frontLeftWheelFrictionCurve.extremumSlip = forwardAsymptoteSlip;
frontLeftWheelFrictionCurve.extremumValue = forwardExtremumValue;
frontLeftWheelFrictionCurve.asymptoteSlip = forwardAsymptoteSlip;
frontLeftWheelFrictionCurve.asymptoteValue = forwardAsymptoteValue;
frontLeftWheelFrictionCurve.stiffness = forwardStiffness;
frontRightWheelFrictionCurv.extremumSlip = forwardAsymptoteSlip;
frontRightWheelFrictionCurv.extremumValue = forwardExtremumValue;
frontRightWheelFrictionCurv.asymptoteSlip = forwardAsymptoteSlip;
frontRightWheelFrictionCurv.asymptoteValue = forwardAsymptoteValue;
frontRightWheelFrictionCurv.stiffness = forwardStiffness;
backLeftWheelFrictionCurv.extremumSlip = forwardExtremumSlip;
backLeftWheelFrictionCurv.extremumValue = forwardExtremumValue;
backLeftWheelFrictionCurv.asymptoteSlip = forwardAsymptoteSlip;
backLeftWheelFrictionCurv.asymptoteValue = forwardAsymptoteValue;
backLeftWheelFrictionCurv.stiffness = forwardStiffness;
backRightWheelFrictionCurv.extremumSlip = forwardExtremumSlip;
backRightWheelFrictionCurv.extremumValue = forwardExtremumValue;
backRightWheelFrictionCurv.asymptoteSlip = forwardAsymptoteSlip;
backRightWheelFrictionCurv.asymptoteValue = forwardAsymptoteValue;
backRightWheelFrictionCurv.stiffness = forwardStiffness;
//Sideways Friction
frontLeftWheelFrictionCurve.extremumSlip = sidewaysExtremumSlip;
frontLeftWheelFrictionCurve.extremumValue = sidewaysExtremumValue;
frontLeftWheelFrictionCurve.asymptoteSlip = sidewaysAsymptoteSlip;
frontLeftWheelFrictionCurve.asymptoteValue = sidewaysAsymptoteValue;
frontLeftWheelFrictionCurve.stiffness = sidewaysStiffness;
frontRightWheelFrictionCurv.extremumSlip = sidewaysExtremumSlip;
frontRightWheelFrictionCurv.extremumValue = sidewaysExtremumValue;
frontRightWheelFrictionCurv.asymptoteSlip = sidewaysAsymptoteSlip;
frontRightWheelFrictionCurv.asymptoteValue = sidewaysAsymptoteValue;
frontRightWheelFrictionCurv.stiffness = sidewaysStiffness;
backLeftWheelFrictionCurv.extremumSlip = sidewaysExtremumSlip;
backLeftWheelFrictionCurv.extremumValue = sidewaysExtremumValue;
backLeftWheelFrictionCurv.asymptoteSlip = sidewaysAsymptoteSlip;
backLeftWheelFrictionCurv.asymptoteValue = sidewaysAsymptoteValue;
backLeftWheelFrictionCurv.stiffness = sidewaysStiffness;
backRightWheelFrictionCurv.extremumSlip = sidewaysExtremumSlip;
backRightWheelFrictionCurv.extremumValue = sidewaysExtremumValue;
backRightWheelFrictionCurv.asymptoteSlip = sidewaysAsymptoteSlip;
backRightWheelFrictionCurv.asymptoteValue = sidewaysAsymptoteValue;
backRightWheelFrictionCurv.stiffness = sidewaysStiffness;
// The rigidbody velocity is always given in world space, but in order to work in local space of the car model we need to transform it first.
Vector3 relativeVelocity = transform.InverseTransformDirection(rigidbody.velocity);
UpdateFriction(relativeVelocity);
}
void UpdateFriction(Vector3 relativeVelocity) {
float sqrVel = relativeVelocity.x * relativeVelocity.x;
// Forward
int maxFStif = 100, minFStif = 70;
frontLeftWheelFrictionCurve.extremumValue = Mathf.Clamp(maxFStif - sqrVel,0,maxFStif);
frontLeftWheelFrictionCurve.asymptoteValue = Mathf.Clamp(minFStif - (sqrVel / 2), 0, minFStif);
frontRightWheelFrictionCurv.extremumValue = Mathf.Clamp(maxFStif - sqrVel, 0, maxFStif);
frontRightWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minFStif - (sqrVel / 2), 0, minFStif);
backLeftWheelFrictionCurv.extremumValue = Mathf.Clamp(maxFStif - sqrVel, 10, maxFStif);
backLeftWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minFStif - (sqrVel / 2), 10, minFStif);
backRightWheelFrictionCurv.extremumValue = Mathf.Clamp(maxFStif - sqrVel, 10, maxFStif);
backRightWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minFStif - (sqrVel / 2), 10, minFStif);
// Add extra sideways friction based on the car's turning velocity to avoid slipping
int maxSStif = 100, minSStif = 50;
frontLeftWheelFrictionCurve.extremumValue = Mathf.Clamp(maxSStif - sqrVel, 10, maxSStif);
frontLeftWheelFrictionCurve.asymptoteValue = Mathf.Clamp(minSStif - (sqrVel / 2), 10, minSStif);
frontRightWheelFrictionCurv.extremumValue = Mathf.Clamp(maxSStif - sqrVel, 10, maxSStif);
frontRightWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minSStif - (sqrVel / 2), 10, minSStif);
backLeftWheelFrictionCurv.extremumValue = Mathf.Clamp(maxSStif - sqrVel, 10, maxSStif);
backLeftWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minSStif - (sqrVel / 2), 10, minSStif);
backRightWheelFrictionCurv.extremumValue = Mathf.Clamp(maxSStif - sqrVel, 10, maxSStif);
backRightWheelFrictionCurv.asymptoteValue = Mathf.Clamp(minSStif - (sqrVel / 2), 10, minSStif);
}
}
------------------------------------------------
WheelSuspension_Script (C#) :
using UnityEngine;
using System.Collections;
public class WheelSuspension_Script : MonoBehaviour {
[SerializeField]
WheelCollider frontLeftWheel, frontRightWheel, backLeftWheel, backRightWheel;
[SerializeField]
float wheelRadius = 0.33f,
springLength = 0.1f,
damperForce = 50f, // 50
springForceFront = 8500f, // 18500
springForceRear = 5000f; // 9000;
JointSpring frontLeftWheelJointSpring, frontRightWheelJointSpring, backLeftWheelJointSpring, backRightWheelJointSpring;
void Start() {
frontLeftWheelJointSpring = frontLeftWheel.suspensionSpring;
frontRightWheelJointSpring = frontRightWheel.suspensionSpring;
backLeftWheelJointSpring = backLeftWheel.suspensionSpring;
backRightWheelJointSpring = backRightWheel.suspensionSpring;
}
// Update is called once per frame
void Update () {
frontLeftWheel.radius = wheelRadius;
frontLeftWheel.suspensionDistance = springLength;
frontLeftWheelJointSpring.spring = springForceFront;
frontLeftWheelJointSpring.damper = damperForce;
frontRightWheel.radius = wheelRadius;
frontRightWheel.suspensionDistance = springLength;
frontRightWheelJointSpring.spring = springForceFront;
frontRightWheelJointSpring.damper = damperForce;
// Rear Suspension
backLeftWheel.radius = wheelRadius;
backLeftWheel.suspensionDistance = springLength;
backLeftWheelJointSpring.spring = springLength;
backLeftWheelJointSpring.damper = damperForce;
backRightWheel.radius = wheelRadius;
backRightWheel.suspensionDistance = springLength;
backRightWheelJointSpring.spring = springLength;
backRightWheelJointSpring.damper = damperForce;
}
}
------------------------------------------------
AICar_Script (C#) :
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(AudioSource))]
public class AICar_Script : MonoBehaviour {
// These variables allow the script to power the wheels of the car.
[SerializeField]
WheelCollider frontLeftWheel, frontRightWheel, backLeftWheel, backRightWheel;
/**
* These variables are for the gears, the array is the list of ratios. The script
uses the defined gear ratios to determine how much torque to apply to the wheels.
*/
[SerializeField]
float[] gearRatio;
[SerializeField]
float differentialRatio = 3.1f;
[SerializeField]
int currentGear = 0;
/**
* These variables are just for applying torque to the wheels and shifting gears.
using the defined Max and Min Engine RPM, the script can determine what gear the
car needs to be in.
*/
[SerializeField]
float engineTorque = 600f,
maxEngineRPM = 3000f,
minEngineRPM = 1000f;
private float engineRPM = 0f;
/**
* Here's all the variables for the AI, the waypoints are determined in the "GetWaypoints" function.
the waypoint container is used to search for all the waypoints in the scene, and the current
waypoint is used to determine which waypoint in the array the car is aiming for.
*/
[SerializeField]
GameObject waypointContainer;
private Transform[] waypoints;
private int currentWaypoint = 0;
/**
* input steer and input torque are the values substituted out for the player input. The
"NavigateTowardsWaypoint" function determines values to use for these variables to move the car
in the desired direction.
*/
private float inputSteer, inputTorque;
Rigidbody rigidbody;
AudioSource audioSource;
void Start () {
// I usually alter the center of mass to make the car more stable. I'ts less likely to flip this way.
rigidbody = GetComponent<Rigidbody>();
rigidbody.centerOfMass = new Vector3(rigidbody.centerOfMass.x, 0.45f, 0.15f);
audioSource = GetComponent<AudioSource>();
/**
* Call the function to determine the array of waypoints. This sets up the array of points by finding
transform components inside of a source container.
*/
getWaypoints();
}
// Update is called once per frame
void Update () {
/**
* This is to limith the maximum speed of the car, adjusting the drag probably isn't the best way of doing it,
but it's easy, and it doesn't interfere with the physics processing.
*/
rigidbody.drag = rigidbody.velocity.magnitude / 250;
/**
* Call the funtion to determine the desired input values for the car. This essentially steers and
applies gas to the engine.
*/
navigateTowardsWaypoint();
// Compute the engine RPM based on the average RPM of the two wheels, then call the shift gear function
engineRPM = (backLeftWheel.rpm + backRightWheel.rpm) / 2 * gearRatio[currentGear] * differentialRatio;
shiftGears();
/**
* set the audio pitch to the percentage of RPM to the maximum RPM plus one, this makes the sound play
up to twice it's pitch, where it will suddenly drop when it switches gears.
*/
audioSource.pitch = Mathf.Abs(engineRPM/maxEngineRPM)+0.5f;
// this line is just to ensure that the pitch does not reach a value higher than is desired.
if (audioSource.pitch > 1.5f)
audioSource.pitch = 1.5f;
/**
* finally, apply the values to the wheels. The torque applied is divided by the current gear, and
multiplied by the calculated AI input variable.
FrontLeftWheel.motorTorque = EngineTorque / GearRatio[CurrentGear]*DifferentialRatio * inputTorque;
FrontRightWheel.motorTorque = EngineTorque / GearRatio[CurrentGear]*DifferentialRatio * inputTorque;
*/
backLeftWheel.motorTorque = -engineTorque / gearRatio[currentGear] * differentialRatio * inputTorque;
backRightWheel.motorTorque = -engineTorque / gearRatio[currentGear] * differentialRatio * inputTorque;
// the steer angle is an arbitrary value multiplied by the calculated AI input.
frontLeftWheel.steerAngle = 35 * inputSteer;
frontRightWheel.steerAngle = 35 * inputSteer;
}
void shiftGears() {
/**
* this funciton shifts the gears of the vehcile, it loops through all the gears, checking which will make
the engine RPM fall within the desired range. The gear is then set to this "appropriate" value.
*/
int appropriateGear;
if (engineRPM >= maxEngineRPM){
appropriateGear = currentGear;
for (int i =0; i < gearRatio.Length; i++) {
if (backLeftWheel.rpm * gearRatio[i] * differentialRatio < maxEngineRPM) {
appropriateGear = i;
break;
}
}
currentGear = appropriateGear;
}
if (engineRPM <= minEngineRPM) {
appropriateGear = currentGear;
for (int j = gearRatio.Length-1; j >= 0; j--){
if (engineRPM <= minEngineRPM){
appropriateGear = j;
break;
}
}
currentGear = appropriateGear;
}
}
void getWaypoints(){
/**
* Now, this function basically takes the container object for the waypoints, then finds all of the transforms in it,
once it has the transforms, it checks to make sure it's not the container, and adds them to the array of waypoints.
*/
Transform[] potentialWaypoints = waypointContainer.GetComponentsInChildren<Transform>();
//waypoints = new Transform[];
foreach (Transform potentialWaypoint in potentialWaypoints) {
if (potentialWaypoint != waypointContainer.transform)
waypoints[waypoints.Length] = potentialWaypoint;
}
}
void navigateTowardsWaypoint() {
/**
* now we just find the relative position of the waypoint from the car transform,
that way we can determine how far to the left and right the waypoint is.
*/
Vector3 relativeWaypointPosition = transform.InverseTransformPoint(new Vector3(waypoints[currentWaypoint].position.x, transform.position.y, waypoints[currentWaypoint].position.z));
// by dividing the horizontal position by the magnitude, we get a decimal percentage of the turn angle that we can use to drive the wheels
inputSteer = relativeWaypointPosition.x / relativeWaypointPosition.magnitude;
// now we do the same for torque, but make sure that it doesn't apply any engine torque when going around a sharp turn...
float value = (Mathf.Abs(inputSteer) < 1.0) ? relativeWaypointPosition.z / relativeWaypointPosition.magnitude - Mathf.Abs(inputSteer) : 0f;
inputTorque = value;
/**
* this just checks if the car's position is near enough to a waypoint to count as passing it, if it is, then change the target waypoint to the
next in the list.
*/
if (relativeWaypointPosition.magnitude < 30){
currentWaypoint++;
if (currentWaypoint >= waypoints.Length)
currentWaypoint = 0;
}
}
}
------------------------------------------------
DrawWaypointGizmos_Script (C#) :
using UnityEngine;
using System.Collections;
public class DrawWaypointGizmos_Script : MonoBehaviour {
void OnDrawGizmos() {
// make a new array of waypoints, then set it to all of the transforms in the current object
Transform waypoints = gameObject.GetComponentInChildren<Transform>();
// now loop through all of them and draw gizmos for each of them
foreach (Transform waypoint in waypoints) {
Gizmos.DrawSphere(waypoint.position, 1.0f);
}
}
}
沒有留言:
張貼留言