I am currently struggling with wheel colliders in Unity on my car. I have tried different code and cars, even made a simple car in Unity. But nothing works as I would have it.
As seen on the pictures, my wheels keep searching into the center on my car and the wheels don't drive around themselves.
Image of my car controller:
Image of my wheel collider:
Image of my wheels:
Image of my wheels in the center of my car:
using UnityEngine;
public class CARController : MonoBehaviour
{
public void GetInput()
{
m_horizontalInput = Input.GetAxis("Horizontal");
m_verticalInput = Input.GetAxis("Vertical");
}
private void Steer()
{
m_steeringangle = maxSteeringAngle * m_horizontalInput;
frontDriverW.steerAngle = m_steeringangle;
frontpassengerW.steerAngle = m_steeringangle;
}
private void Accelerate()
{
frontDriverW.motorTorque = m_verticalInput * motorForce;
frontpassengerW.motorTorque = m_verticalInput * motorForce;
}
private void UpdateWheelPoses()
{
UpdateWheelPose(frontDriverW, frontDriverT);
UpdateWheelPose(frontpassengerW, frontpassengerT);
UpdateWheelPose(rearDriverW, rearDriverT);
UpdateWheelPose(rearPassengerW, rearpassengerT);
}
private void UpdateWheelPose(WheelCollider _collider, Transform _transform)
{
Vector3 _pos = _transform.position;
Quaternion _quat = _transform.rotation;
_collider.GetWorldPose(out _pos, out _quat);
_transform.position = _pos;
_transform.rotation = _quat;
}
private void FixedUpdate()
{
GetInput();
Steer();
Accelerate();
UpdateWheelPoses();
}
private float m_horizontalInput;
private float m_verticalInput;
private float m_steeringangle;
public WheelCollider frontDriverW, frontpassengerW;
public WheelCollider rearDriverW, rearPassengerW;
public Transform frontDriverT, frontpassengerT;
public Transform rearDriverT, rearpassengerT;
public float maxSteeringAngle = 30;
public float motorForce = 50;
}
Above here is the code of my engine to the car.
This usually happens when the wheel mesh axis is in the wrong place when using Pivot and local rotation below the menu options in the editor.
Try creating a cylinder and position it where the wheel is at. Then remove its renderer and filter and parent the actual wheel of the cylinder transform. Drag the cylinder as the wheel transform in inspector.