- Home /
Rotating player with Quaternion and RotateTowards
My 3D character is a Cow and can be pushed away by a collision, in which i'll apply a Force and Torque so that the character can be knocked back approprially. When the character enters collision, it goes into a 'Ball' position, in which it just rolls around like a ball. This i'm achieving already. However, now I wanted to rotate the Cow in such way that it is able to transition into the normal/walkable position. For example if the Cow is in the Ball position, with its belly up, facing forward in the World, i just want to rotate around the Z axis so that the belly is facing down, and now I can transition into normal/walkable position. I am already rotating the player, but for some reason, after rotation, the character ends up always facing forward in world coordinates but that's not what I wanted. I want that, if the character is facing to the right with the belly up, it will still face that direction but with the belly down. How can i achieve this? I think im close but can't get there.
private IEnumerator StandUp() {
float yRot = rb.rotation.y;
Quaternion targetRotation = Quaternion.Euler(0, yRot, 0);
Vector3 direction = targetRotation * Vector3.forward;
while (Vector3.Angle(transform.forward, direction) > 1) {
rb.rotation = Quaternion.RotateTowards(rb.rotation, targetRotation, 8f);
yield return new WaitForSeconds(0.00f);
}
{ ... } // animator controller -> set normal/walking state
}
Answer by Serge144 · Sep 29, 2020 at 09:07 PM
Fixed it lol the yRot variable should be:
float yRot = rb.rotation.eulerAngles.y;
Still some improvements to be made though, 10% of the times it doesn't fully go to the normal position and it rotates until it gets sideways (like it was sleeping).
EDIT Fixed the issue i mentioned above (of not going fully to the normal position), I changed the while condition to this:
while (Quaternion.Angle(rb.rotation, targetRotation) > 2)