unity汽车刹车后加速问题

问题描述

我有一个汽车物理课,附有车轮对撞机。我已经在检查器上将“maxMotorTorque”值设置为 150,“maxSteeringAngle”为 30,“brake”为 150。这是我从 unity Wheel colliders 教程中复制的简单代码,并添加了刹车。当我按下空格键并激活刹车时,我的车停下了,但即使我按下了“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);
    }
}

}

解决方法

这是因为你只有在按下空格键时才会调用 Braking,一旦玩家停止按下空格键,它就不会再进入 Braking 功能,你将它设置为 {{1 }} 仅在 brakeTorque 时设置 因此添加以下代码:

isBraking == false

这样,当玩家松开空格键并且 if (Input.GetKey(KeyCode.Space)) { isBraking = true; Braking(axleInfo); } else if(Input.GetKeyUp(KeyCode.Space)){ isBraking = false; Braking(axleInfo); } 设置为 0 时,将调用一次 Braking

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...