0

我有一个汽车物理课,它附有车轮对撞机。我已将检查器的“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);
    }
}

}

4

1 回答 1

1

这是因为您仅在按下空格键时才调用 Braking,一旦玩家停止按下空格键,它将不再进入 Braking 功能并且您设置它以便brakeTorque仅在isBraking == false 添加时设置以下代码:

 if (Input.GetKey(KeyCode.Space))
 {
     isBraking = true;
     Braking(axleInfo);
 }
 else if(Input.GetKeyUp(KeyCode.Space)){
     isBraking = false;
     Braking(axleInfo);
 }

这样当玩家释放空格键并brakeTorque设置为 0时会调用一次 Braking

于 2021-03-05T12:37:17.737 回答