效果:
小提示:[SerializeField] private speed 功能是在外面inspector窗口看到以及为脚本代码里相应的私有组件进行赋值操作
# 说明:ws或上下方向键控制前后动力,ad或左右方向键控制左右转向,空格刹车。汽车整体需挂载刚体和碰撞组件,轮胎父物体需挂载车轮碰撞器即可,轮胎不需要理会。
2,模型场景搭建
导入小车模型,解掉预制体(方便在已绑定的物体进行操作)
3,给汽车整体添加刚体组件和碰撞体组件,注意调整汽车质量和碰撞体的范围
4,给每个车轮创建各自的空父物体并为空父物体添加车轮碰撞体WhellColliderb用于调整车轮碰撞体的位置和大小
5,让车轮碰撞器刚好贴合轮胎
6,完整代码
using UnityEngine;
public class car : MonoBehaviour
{
[SerializeField] private WheelCollider flWheelCollider;
[SerializeField] private WheelCollider frWheelCollider;
[SerializeField] private WheelCollider rlWheelCollider;
[SerializeField] private WheelCollider rrWheelCollider;
//这几行是为了能让后边直接引用其车轮碰撞体的属性
//不然还得用其游戏物体用GetComponent 的方式引用其组件属性
//例如:区别一二两句代码就能知道我的意思了
// 一,flWheelTransform.Rotate(FLWheel.GetComponent<WheelCollider>().rpm * 360 * Time.deltaTime,0, 0 );
// 二,frWheelTransform.Rotate(frWheelCollider.rpm * 360 * Time.deltaTime,0, 0);
public GameObject BRWheel, FRWheel;
public GameObject BLWheel, FLWheel;
public float maxMortetorque = 300f;
public float maxSteerAngle = 30f;
public float maxBrakeTorque = 500f;
float motor, steer, brake;
//motor 是前进动力
//steer 是转向
//brake 是刹车动力
void Update()
{
motor = maxMortetorque * Input.GetAxis("Vertical");//垂直虚拟轴进行前后移动
steer = maxSteerAngle * Input.GetAxis("Horizontal"); //水平虚拟轴进行转向
brake = maxBrakeTorque * Input.GetAxis("Jump");//空格键刹车
BRWheel.GetComponent<WheelCollider>().motorTorque = motor;
BLWheel.GetComponent<WheelCollider>().motorTorque = motor;
FRWheel.GetComponent<WheelCollider>().steerAngle = steer;
FLWheel.GetComponent<WheelCollider>().steerAngle = steer;
BRWheel.GetComponent<WheelCollider>().brakeTorque = brake;
BLWheel.GetComponent<WheelCollider>().brakeTorque = brake;
//车轮模型转动
flWheelTransform.Rotate(FLWheel.GetComponent<WheelCollider>().rpm * 360 * Time.deltaTime,0, 0 );
frWheelTransform.Rotate(frWheelCollider.rpm * 360 * Time.deltaTime,0, 0);
rlWheelTransform.Rotate(rlWheelCollider.rpm * 360 * Time.deltaTime,0, 0);
rrWheelTransform.Rotate(rrWheelCollider.rpm * 360 * Time.deltaTime,0, 0 );
//rrWheelTransform.Rotate(rrWheelCollider.rpm/60 * 360 * Time.deltaTime * Vector3.forward);
}
}