- Home /
Move rigidbody whilst keeping it upright
I have a 2D game, where a rigidbody attached to a sprite needs to be moved. How do I go about keeping the sprite right side up regardless of how ridiculous the incline is?
Thank you in advance!
Answer by GameVortex · Jan 14, 2014 at 12:52 PM
It is not perfect, but you could do a raycast downwards each frame and rotate the object to align with the normal of the hit object. This of course basically overrides all rotation based on physics, so you should just as well freeze all physics rotation on the object.
Example:
private void FixedUpdate()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit, 100))
{
rigidbody.rotation = Quaternion.LookRotation(Vector3.forward, hit.normal);
}
}
I have not spent much time in 2D yet, but the principle is the same as in 3D.
You can improve the accuracy by raycasting towards the object's relative down, assu$$anonymous$$g the change each frame is small, it will be more accurate than raycasting towards Vector3.down:
if (Physics.Raycast(transform.position, -transform.up, out hit, 100))