I'm fairly new to Unity and game development in general, I'm trying to build a basic car and give visual movement to the wheels. The car controls are pretty basic: accelerate "w" key, turn right "d" key, turn left "a" key, decelerate "s" key. The wheel moves and turns according to the key pressed, but the problem is that the wheel changes its position during the game mode. I am only working with one wheel until I know how to do this correctly.
The player object has a Rigidbody component and the movement script, also is composed by two childs objects: the car body, this object has a mesh collider component, and the wheels, this object also has their own child objects: wheel colliders and wheel models.
This is what the wheels look like from edit mode:
And this is how the wheels look like from play mode:
Code from the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleCarController : MonoBehaviour
{
[SerializeField] private Rigidbody _rb;
[SerializeField] Transform frontLeftTransform;
[SerializeField] Transform backLeftTransform;
[SerializeField] WheelCollider frontLeft;
[SerializeField] WheelCollider frontRight;
[SerializeField] WheelCollider backLeft;
[SerializeField] WheelCollider backRight;
public float acceleration = 500f;
public float breakingForce = 300f;
public float maxTurnAngle = 50f;
private float currentAcceleration = 0f;
private float currentBreakForce = 0f;
private float currentTurnAngle = 0f;
void Start()
{
_rb = GetComponent<Rigidbody>();
}
public void FixedUpdate()
{
currentAcceleration = acceleration * -Input.GetAxis("Vertical");
backRight.motorTorque = currentAcceleration;
backLeft.motorTorque = currentAcceleration;
if (Input.GetKey(KeyCode.Space))
currentBreakForce = breakingForce;
else
currentBreakForce = 0;
frontRight.brakeTorque = currentBreakForce;
frontLeft.brakeTorque = currentBreakForce;
backLeft.brakeTorque = currentBreakForce;
backRight.brakeTorque = currentBreakForce;
currentTurnAngle = maxTurnAngle * Input.GetAxis("Horizontal");
frontLeft.steerAngle = currentTurnAngle;
frontRight.steerAngle = currentTurnAngle;
UpdateWheel(frontLeft, frontLeftTransform);
UpdateWheel(backLeft, backLeftTransform);
}
void UpdateWheel(WheelCollider col, Transform transform)
{
Vector3 pos;
Quaternion rot;
col.GetWorldPose(out pos, out rot);
transform.position = pos;
transform.rotation = rot;
}
}
I don' know why this, any help is appreciated.
--UPDATE-- Image with gizmo in Local/Pivot: