I've been learning unity and 3d modelling over the last couple of months and I'm trying to set up a basic car game using raycasts, as the wheel colliders in unity aren't great.
Right now I'm trying to get the wheel mesh (wheelTransform in the code) to rotate with as the car moves.
I have the following line to get the speed of the car at the point where the raycast hits the ground in the local space of the car, in the direction that the car is facing.
wheelForwardVelocity = transform.InverseTransformDirection(carRigidbody.GetPointVelocity(hit.point)).z;
Then I have the following line to calculate how much the wheel must rotate each frame depending on wheelForwardVelocity. I am not implementing wheel slip at this point so I can just have the wheel rotate based on the car speed.
wheelRotationAngleAddition = (wheelForwardVelocity * 360 * Time.deltaTime) / (Mathf.PI * 2 * wheelRadius);
Finally I have the following 3 lines to add change the wheels rotation:
Vector3 rotation = wheelTransform.localRotation.eulerAngles;
rotation.x += wheelRotationAngleAddition;
wheelTransform.localRotation = Quaternion.Euler(rotation);
However, when I test the game in Unity the wheel rotation does not work:
At slow speeds, the wheel rotation seems to be right, but then it will (seemingly at random) start freaking out rotating back and forth. I cannot for the life of me figure out why! I would really appreciate any help :)