Game Development Asked by John 545 on November 29, 2021
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 🙂
Your rotation code looks like this:
Vector3 rotation = wheelTransform.localRotation.eulerAngles;
rotation.x += wheelRotationAngleAddition;
wheelTransform.localRotation = Quaternion.Euler(rotation);
Unity specifically recommends not changing the rotation in this manner, because of the possibility of gimbal lock and other conversion errors when converting back and forth with Euler angles. See example #2 of what not to do in the documentation, which looks almost exactly the same as your code.
A safer way is to use transform.Rotate()
:
wheelTransform.Rotate(wheelRotationAngleAddition, 0, 0);
Answered by Kevin on November 29, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP