I have a car physics class which is wheel colliders attached. I've set the "maxMotorTorque" value to 150, "maxSteeringAngle" to 30 and "brake" to 150 on the inspector. This is a simple code I copied from the unity wheel colliders tutorial and I added brake. When I press space key and make the brake active, my car stops but my car is not accelerating again even though I press the "W" and "S" keys. Here is my code:
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);
}
}
}
this is due to the fact that you only call Braking if the space key is pressed, as soon as the player stops pressing the space key it will not go into the Braking function anymore and you set it up so that
brakeTorque
is only set ifisBraking == false
therefore add following code:this way Braking will be called once when the player releases the space key and
brakeTorque
is set to 0