- Home /
2D Physics Rotate Sprite Level With Floor
I need to, using the 2D Physics, make my player rotate so that it is level with the floor. I've seen solutions before, but all of the use 3D Physics. I'm using 2D Physics and my camera is facing positive Z. I can't just set the sprite's Z to the ground's though, I need to use the transform.normal or something.
Answer by robcbryant · Mar 29, 2014 at 07:21 PM
You shouldn't need to be worrying about the z at all--in transformation terms. I'm not entirely sure what you're getting at--but I think I do. If your sprite is a quad (a flat square) and you are rotating it with physics all the time and need to 'reset' it to be flat with the ground couldn't you just set the rotation(I think the z axis) back to zero?
Here's a quick easy fix.
//this goes before the Update() loop because you don't want it changing every update
private Quaternion zeroRotation = whateverGameObject.transform.rotation;
//when it's time to make the sprite 'level' with the ground again just set the rotation back to this
whateverGameObject.transform.rotation = zeroRotation;
Dealing with rotations can be difficult--when I can I try to use a placeholder Quaternion variable rather than figure out the very complicated math behind it.
*EDIT: I think now--you mean you want the physics to auto rotate the sprite back to 'zero' --not just change it immediately to zero -- ie. a smooth turn to zero. You can use the same placeholder quaternion for your zero position and rotate the sprite along the axis in question(I'm assuming z) and check if it's at the zero position or not--if it is then stop rotating.
Update() {
//check if the transform is at the zero rotation
if(transform.rotation != zeroPosition)
// Slowly rotate the object around its z axis at 1 degree/second.
transform.Rotate(Vector3.up * Time.deltaTime);
}
I will say that if physics are involved--your quaternion may not be an integer--so you would potentially never be equal to the zeroPosition quaternion. You can look into doing a looser comparison with some buffer room ie. 1 degree of wiggle room--but this is a quick answer. Note that this will always attempt to rotate the sprite back to zero indefinitely--so you may want to set a trigger for it specifically--I don't know all the details.
Your answer
Follow this Question
Related Questions
How to get a ball with physics2d to move instead of spin? 1 Answer
Rotating Children as Rigidbodies2D because transform rotation is too costly 0 Answers
How to rotate my 2d gameObject using touch input?? 1 Answer
Photon Syncing rotating projectile 2D 1 Answer
Making sprites just rotate and not tilt. 3 Answers