Player Car (JS):
// These variables allow the script to power the wheels of the car.
var FrontLeftWheel : WheelCollider;
var FrontRightWheel : WheelCollider;
var BackLeftWheel : WheelCollider;
var BackRightWheel : WheelCollider;
// 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.
var GearRatio : float[];
var DifferentialRatio : float = 3.21;
var CurrentGear : int = 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.
var EngineTorque : float = 600.0;
var MaxEngineRPM : float = 7000.0;
var MinEngineRPM : float = 1000.0;
var EngineRPM : float = 0.0;
var FrontWheelDrive : int = 1;
var RearWheelDrive : int = 1;
// Center Of Mass
var COMX : float = 0;
var COMY : float = -0.2;
var COMZ : float = 0.5;
function Start () {
// I usually alter the center of mass to make the car more stable. I'ts less likely to flip this way.
GetComponent.<Rigidbody>().centerOfMass.x = COMX;
GetComponent.<Rigidbody>().centerOfMass.y = COMY;
GetComponent.<Rigidbody>().centerOfMass.z = COMZ;
}
function Update () {
//update center of mass
GetComponent.<Rigidbody>().centerOfMass.x = COMX;
GetComponent.<Rigidbody>().centerOfMass.y = COMY;
GetComponent.<Rigidbody>().centerOfMass.z = 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.
GetComponent.<Rigidbody>().drag = GetComponent.<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.
GetComponent.<AudioSource>().pitch = Mathf.Abs(EngineRPM / MaxEngineRPM) + 0.5 ;
// this line is just to ensure that the pitch does not reach a value higher than is desired.
if ( GetComponent.<AudioSource>().pitch > 1.5 ) {
GetComponent.<AudioSource>().pitch = 1.5;
}
// 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) {
FrontLeftWheel.motorTorque = -EngineTorque * GearRatio[CurrentGear]*DifferentialRatio * Input.GetAxis("Vertical");
FrontRightWheel.motorTorque = -EngineTorque * GearRatio[CurrentGear]*DifferentialRatio * Input.GetAxis("Vertical");
}
if (RearWheelDrive) {
BackLeftWheel.motorTorque = -EngineTorque * GearRatio[CurrentGear] * DifferentialRatio * Input.GetAxis("Vertical");
BackRightWheel.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");
}
function 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 ) {
var AppropriateGear : int = CurrentGear;
for ( var i = 0; i < GearRatio.length; i ++ ) {
if ( Mathf.Abs(BackLeftWheel.rpm + BackRightWheel.rpm)/2 * GearRatio[i]*DifferentialRatio < MaxEngineRPM ) {
AppropriateGear = i;
break;
}
}
CurrentGear = AppropriateGear;
}
if ( EngineRPM <= MinEngineRPM ) {
AppropriateGear = CurrentGear;
for ( var j = GearRatio.length-1; j >= 0; j -- ) {
if ( Mathf.Abs(BackLeftWheel.rpm + BackRightWheel.rpm)/2 * GearRatio[j]*DifferentialRatio > MinEngineRPM ) {
AppropriateGear = j;
break;
}
}
CurrentGear = AppropriateGear;
}
}
----------------------------------------
※ 這是輪胎(有用前後輪,另外給參數)
WheelAntiRoll (JS):
var WheelR : WheelCollider;
var AntiRoll = 5000.0;
function FixedUpdate ()
{
var hit : WheelHit;
var travelL = 1.0;
var travelR = 1.0;
var groundedL = WheelL.GetGroundHit(hit);
if (groundedL)
travelL = (-WheelL.transform.InverseTransformPoint(hit.point).y - WheelL.radius) / WheelL.suspensionDistance;
var groundedR = WheelR.GetGroundHit(hit);
if (groundedR)
travelR = (-WheelR.transform.InverseTransformPoint(hit.point).y - WheelR.radius) / WheelR.suspensionDistance;
var antiRollForce = (travelL - travelR) * AntiRoll;
if (groundedL)
GetComponent.<Rigidbody>().AddForceAtPosition(WheelL.transform.up * -antiRollForce,
WheelL.transform.position);
if (groundedR)
GetComponent.<Rigidbody>().AddForceAtPosition(WheelR.transform.up * antiRollForce,
WheelR.transform.position);
}
------------------------------------
※ 攝影機腳本
SmoothFollow(JS):
/*
This camera smoothes out rotation around the y-axis and height.
Horizontal Distance to the target is always fixed.
There are many different ways to smooth the rotation but doing it this way gives you a lot of control over how the camera behaves.
For every of those smoothed values we calculate the wanted value and the current value.
Then we smooth it using the Lerp function.
Then we apply the smoothed values to the transform's position.
*/
// The target we are following
var target : Transform;
// The distance in the x-z plane to the target
var distance = 10.0;
// the height we want the camera to be above the target
var height = 5.0;
// How much we
var heightDamping = 2.0;
var rotationDamping = 3.0;
// Place the script in the Camera-Control group in the component menu
@script AddComponentMenu("Camera-Control/Smooth Follow")
function LateUpdate () {
// Early out if we don't have a target
if (!target)
return;
// Calculate the current rotation angles
var wantedRotationAngle = target.eulerAngles.y;
var wantedHeight = target.position.y + height;
var currentRotationAngle = transform.eulerAngles.y;
var currentHeight = transform.position.y;
// Damp the rotation around the y-axis
currentRotationAngle = Mathf.LerpAngle (currentRotationAngle, wantedRotationAngle, rotationDamping * Time.deltaTime);
// Damp the height
currentHeight = Mathf.Lerp (currentHeight, wantedHeight, heightDamping * Time.deltaTime);
// Convert the angle into a rotation
var currentRotation = Quaternion.Euler (0, currentRotationAngle, 0);
// Set the position of the camera on the x-z plane to:
// distance meters behind the target
transform.position = target.position;
transform.position -= currentRotation * Vector3.forward * distance;
// Set the height of the camera
transform.position.y = currentHeight;
// Always look at the target
transform.LookAt (target);
}
----------------------------------
※ 放在車子上的物件
AI Car (JS):
// These variables allow the script to power the wheels of the car.
var FrontLeftWheel : WheelCollider;
var FrontRightWheel : WheelCollider;
var BackLeftWheel : WheelCollider;
var BackRightWheel : WheelCollider;
// 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.
var GearRatio : float[];
var DifferentialRatio : float = 3.1;
var CurrentGear : int = 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.
var EngineTorque : float = 600.0;
var MaxEngineRPM : float = 3000.0;
var MinEngineRPM : float = 1000.0;
private var EngineRPM : float = 0.0;
// 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.
var waypointContainer : GameObject;
private var waypoints : Array;
private var currentWaypoint : int = 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 var inputSteer : float = 0.0;
private var inputTorque : float = 0.0;
function Start () {
// I usually alter the center of mass to make the car more stable. I'ts less likely to flip this way.
GetComponent.<Rigidbody>().centerOfMass.y = -.45;
GetComponent.<Rigidbody>().centerOfMass.z = -0.15;
// 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();
}
function 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.
GetComponent.<Rigidbody>().drag = GetComponent.<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.
GetComponent.<AudioSource>().pitch = Mathf.Abs(EngineRPM / MaxEngineRPM) + 0.5 ;
// this line is just to ensure that the pitch does not reach a value higher than is desired.
if ( GetComponent.<AudioSource>().pitch > 1.5 ) {
GetComponent.<AudioSource>().pitch = 1.5;
}
// 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;
}
function 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 ) {
var AppropriateGear : int = CurrentGear;
for ( var i = 0; i < GearRatio.length; i ++ ) {
if ( BackLeftWheel.rpm * GearRatio[i]*DifferentialRatio < MaxEngineRPM ) {
AppropriateGear = i;
break;
}
}
CurrentGear = AppropriateGear;
}
if ( EngineRPM <= MinEngineRPM ) {
AppropriateGear = CurrentGear;
for ( var j = GearRatio.length-1; j >= 0; j -- ) {
if ( BackLeftWheel.rpm * GearRatio[j]*DifferentialRatio > MinEngineRPM ) {
AppropriateGear = j;
break;
}
}
CurrentGear = AppropriateGear;
}
}
function 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.
var potentialWaypoints : Array = waypointContainer.GetComponentsInChildren( Transform );
waypoints = new Array();
for ( var potentialWaypoint : Transform in potentialWaypoints ) {
if ( potentialWaypoint != waypointContainer.transform ) {
waypoints[ waypoints.length ] = potentialWaypoint;
}
}
}
function 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.
var RelativeWaypointPosition : Vector3 = transform.InverseTransformPoint( 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...
if ( Mathf.Abs( inputSteer ) < 1.0 ) {
inputTorque = RelativeWaypointPosition.z / RelativeWaypointPosition.magnitude - Mathf.Abs( inputSteer );
}else{
inputTorque = 0.0;
}
// 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;
}
}
}
------------------------------------
※AI 路徑
DrawWaypointGizmos(JS):
function OnDrawGizmos () {
// make a new array of waypoints, then set it to all of the transforms in the current object
var waypoints = gameObject.GetComponentsInChildren( Transform );
// now loop through all of them and draw gizmos for each of them
for ( var waypoint : Transform in waypoints ) {
Gizmos.DrawSphere( waypoint.position, 1.0 );
}
}
-----------------------------------
介面設定:
後輪(Left):
後輪(Right):
前輪(Left):
前輪(Right):
專案圖示:
沒有留言:
張貼留言