using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CarController : MonoBehaviour {
//四个车轮碰撞器---前两个,后两个
public WheelCollider flWheelCollider;
public WheelCollider frWheelCollider;
public WheelCollider rlWheelCollider;
public WheelCollider rrWheelCollider;
/// <summary>
/// 刹车的力矩
/// </summary>
public float maxTorque = 150.0f;
/// <summary>
/// 最大刹车力矩
/// </summary>
public float maxBrakeTorque = 500.0f;
/// <summary>
/// 车轮转向角
/// </summary>
public float maxSteerAngle = 30.0f;
public float maxSpeedSteerAngle = 10.0f;
/// <summary>
/// 前进最大速度
/// </summary>
public float maxSpeed = 200.0f;
/// <summary>
/// 后退最大速度
/// </summary>
public float maxBackwardSpeed = 40.0f;
/// <summary>
/// 当前速度
/// </summary>
public float currentSpeed = 0.0f;
/// <summary>
/// 是否刹车
/// </summary>
private bool isBraking = false;
public float centerOfMassY = 0;
void Awake()
{
//设置小车重心
rigidbody.centerOfMass = new Vector3(0, centerOfMassY, 0);
}
void FixedUpdate()
{
//速度
currentSpeed = (Mathf.PI * 2 * flWheelCollider.radius) * flWheelCollider.rpm * 60 / 1000;
currentSpeed = Mathf.Round(currentSpeed);
//速度大于0并且按下后退键<S>,或者速度小于0并且按下前进键<W>
if (((currentSpeed > 0) && (Input.GetAxis("Vertical") < 0)) || ((currentSpeed < 0) && (Input.GetAxis("Vertical") > 0)))
{
isBraking = true;
}
else
{
isBraking = false;
//设置刹车力为0
flWheelCollider.brakeTorque = 0;
frWheelCollider.brakeTorque = 0;
}
if (isBraking == false)
{
//速度小于最大速度
if ((currentSpeed < maxSpeed) && (currentSpeed > (maxBackwardSpeed * -1)))
{
//让车辆向前滚动
flWheelCollider.motorTorque = maxTorque * Input.GetAxis("Vertical");
frWheelCollider.motorTorque = maxTorque * Input.GetAxis("Vertical");
}
else
{
//不继续增加滚动力
flWheelCollider.motorTorque = 0;
frWheelCollider.motorTorque = 0;
}
}
else
{
//刹车
flWheelCollider.brakeTorque = maxBrakeTorque;
frWheelCollider.brakeTorque = maxBrakeTorque;
flWheelCollider.motorTorque = 0;
frWheelCollider.motorTorque = 0;
}
float speedProcent = currentSpeed / maxSpeed;
speedProcent = Mathf.Clamp(speedProcent, 0, 1);
float speedControlledMaxSteerAngle;
speedControlledMaxSteerAngle = maxSteerAngle - ((maxSteerAngle - maxSpeedSteerAngle) * speedProcent);
flWheelCollider.steerAngle = speedControlledMaxSteerAngle * Input.GetAxis("Horizontal");
frWheelCollider.steerAngle = speedControlledMaxSteerAngle * Input.GetAxis("Horizontal");
}
private void OnGUI()
{
GUILayout.Label(currentSpeed.ToString());
}
}