using UnityEngine;
using System.Collections;
using System.Collections.Generic;
//教程网址 https://docs.unity3d.com/Manual/WheelColliderTutorial.html
[System.Serializable]
public class SimpleCarController : MonoBehaviour
{
public List<AxleInfo> axleInfos; // the information about each individual axle
public float maxMotorTorque; // maximum torque the motor can apply to wheel 车轮上的最大动力
public float maxSteeringAngle; // maximum steer angle the wheel can have 最大转角
public void FixedUpdate()
{
float motor = maxMotorTorque * Input.GetAxis("Vertical");
float steering = maxSteeringAngle * Input.GetAxis("Horizontal");
foreach (AxleInfo axleInfo in axleInfos)
{
if (axleInfo.steering)
{
axleInfo.leftWheel.steerAngle = steering;
axleInfo.rightWheel.steerAngle = steering;
}
if (axleInfo.motor)
{
axleInfo.leftWheel.motorTorque = motor;
axleInfo.rightWheel.motorTorque = motor;
}
ApplyLocalPositionToVisuals(axleInfo.leftWheel);
ApplyLocalPositionToVisuals(axleInfo.rightWheel);
}
}
// finds the corresponding visual wheel
// correctly applies the transform
public void ApplyLocalPositionToVisuals(WheelCollider collider)
{
if (collider.transform.childCount == 0)
{
return;
}
Transform visualWheel = collider.transform.GetChild(0);
Vector3 position;
Quaternion rotation;
collider.GetWorldPose(out position, out rotation);
visualWheel.transform.position = position;
//visualWheel.transform.rotation = rotation;
}
}
//侧轮轱辘
[System.Serializable]
public class AxleInfo
{
public WheelCollider leftWheel;//左轮
public WheelCollider rightWheel;//右轮
public bool motor; // is this wheel attached to motor? 是否提供动能
public bool steering; // does this wheel apply steer angle? 是否能转向
}
创建车子,模型和车轮碰撞器分开,方便操作
在Car上挂载脚本,配置如下:
运行,俺wasd即可移动转弯,在地面上放些障碍物,还可实现颠簸效果