ホイールコライダーが取り付けられた車の物理クラスがあります。インスペクタで「maxMotorTorque」の値を 150、「maxSteeringAngle」を 30、「brake」を 150 に設定しました。これは、ユニティ ホイール コライダーのチュートリアルからコピーした単純なコードで、ブレーキを追加しました。スペースキーを押してブレーキをかけると、車は止まりますが、「W」キーと「S」キーを押しても、車は再び加速しません。これが私のコードです:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class AxleInfo
{
public WheelCollider leftWheel;
public WheelCollider rightWheel;
public bool motor;
public bool steering;
}
public class CarPhysic : MonoBehaviour
{
public List<AxleInfo> axleInfos;
public float maxMotorTorque;
public float maxSteeringAngle;
public float brake;
public bool isBraking;
// 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;
}
private void Braking(AxleInfo axleInfo)
{
if (isBraking)
{
axleInfo.leftWheel.brakeTorque = brake;
axleInfo.rightWheel.brakeTorque = brake;
}
else
{
axleInfo.leftWheel.brakeTorque = 0;
axleInfo.rightWheel.brakeTorque = 0;
}
}
public void FixedUpdate()
{
float motor = maxMotorTorque * Input.GetAxis("Vertical");
float steering = maxSteeringAngle * Input.GetAxis("Horizontal");
foreach (AxleInfo axleInfo in axleInfos)
{
if (axleInfo.steering)
{
isBraking = false;
axleInfo.leftWheel.steerAngle = steering;
axleInfo.rightWheel.steerAngle = steering;
}
if (axleInfo.motor)
{
isBraking = false;
axleInfo.leftWheel.motorTorque = motor;
axleInfo.rightWheel.motorTorque = motor;
}
if (Input.GetKey(KeyCode.Space))
{
isBraking = true;
Braking(axleInfo);
}
ApplyLocalPositionToVisuals(axleInfo.leftWheel);
ApplyLocalPositionToVisuals(axleInfo.rightWheel);
}
}
}