- Home /
Vehicle controller not working well
I am working on a racing game and have an issue with the vehicle controller. When the car gets moving the brake becomes very unresponsive and the car will keep accelerating until it hits something or spins out. The steering continues to work perfectly when moving but the acceleration seems to lock for some reason.
The code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Axel
{
Front,
Rear
}
[Serializable] public struct Wheel
{
public Transform model;
public WheelCollider collider;
public Axel axel;
}
public class CarController : MonoBehaviour
{
private Rigidbody _rigidbody;
[SerializeField] private Transform _centerOfMass;
[SerializeField] private float motorTorque = 1500f, maxSteer = 20f, breakTorque = 2500f;
[SerializeField] private List<Wheel> wheels;
[SerializeField] private bool allWheelDrive = false;
[SerializeField] private bool isBreaking;
private float horizontalInput, verticalInput;
void Start()
{
_rigidbody = GetComponent<Rigidbody>();
_rigidbody.centerOfMass = _centerOfMass.localPosition;
}
void Update()
{
UpdateWheels();
}
void FixedUpdate()
{
GetInput();
Move();
Steer();
}
void GetInput()
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
isBreaking = Input.GetKey(KeyCode.Space);
}
void Move()
{
foreach (var wheel in wheels)
{
if (allWheelDrive)
{
wheel.collider.motorTorque = verticalInput * motorTorque;
if (isBreaking)
{
ApplyBreaking(breakTorque);
}
else
{
ApplyBreaking(0f);
}
}
else
{
if (wheel.axel == Axel.Rear)
{
wheel.collider.motorTorque = verticalInput * motorTorque;
if (isBreaking)
{
ApplyBreaking(breakTorque);
}
else
{
ApplyBreaking(0f);
}
}
}
}
}
void Steer()
{
foreach (var wheel in wheels)
{
if (wheel.axel == Axel.Front)
{
var _steerAngle = horizontalInput * maxSteer;
wheel.collider.steerAngle = Mathf.Lerp(wheel.collider.steerAngle, _steerAngle, 0.5f);
}
}
}
void UpdateWheels()
{
foreach (var wheel in wheels)
{
Vector3 _pos;
Quaternion _rot;
wheel.collider.GetWorldPose(out _pos, out _rot);
wheel.model.position = _pos;
wheel.model.rotation = _rot;
}
}
void ApplyBreaking(float breakTorque)
{
foreach (var wheel in wheels)
{
if (wheel.axel == Axel.Rear)
{
wheel.collider.brakeTorque = breakTorque;
}
}
}
}
Are you already debug your input? it is already in a condition you want it?
is your input work, then try to call apply breaking in update, it is breaking?
If the both work, well, i did not see anything wrong about your codes.
Your answer
![](https://koobas.hobune.stream/wayback/20220613030512im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Need help making only one car drive at a time 0 Answers
Sci Fi Racing Controls and Physics? 0 Answers
Guiding a sphere 2 Answers
Racing Turn Movement 1 Answer