- Home /
How to use rotations in 2D?
When using quaternions in 2D, only one of the axis are used. How do I translate the normal one axis rotations used in 2D games to the quaternion used by the Sprite.transform.rotation? I'm specifically thinking of instantiating a missile in a direction, but I don't know what rotation to use.
Answer by robertbu · Jan 23, 2014 at 05:21 PM
Quaternion.AngleAxis() works. Use Vector3.forward as the axis. Given a vector from your origin, Mathf.Atan2 will calculate an angle. Vector3.right is the 0.0 degree reference for that rotation. Atan2() returns radians, so be sure to use Mathf.Rad2Deg with the result.
If you are using 3D objects in a 2D setup where the 'forward' of those objects aim a positive 'z' when the roation is (0,0,0), then Transform.LookAt() and Quaternion.LookRotation() will work. Both functions have an optional second parameter that defines 'up'. For 2D on the XY plane, you need this optional second parameter, and it should be set to Vector3.forward.
So if you have a direction for your missle, the code might look like:
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vectore3.forward);
This assumes that the head of the missile points towards Vector3.right when the rotation is (0,0,0).
If you are using a 3D missile of the correct rotation, then the code might be:
transform.rotation = Quaternion.LookRotation(dir, Vector3.forward);
Had the same Problem, and this worked perfectly fine, However if I test this in $$anonymous$$ultiplayer, it only works for the Host, not the client (with dedicated server no client works), Its really funny to watch, as it looks like it tries to work, but is just a bit off, Any Idea on what causes this problem?
Edit: seems like the differenc in screenresolution is the problem, as I use
Vector2 targetPosition = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
targetPosition = cam.ScreenToWorldPoint(targetPosition);
to get the position of the target and if the clients use a different one as the server, the calculations are a bit off. It works if all clients use fullscreen (only tested on my PC with only one monitor)
Your answer
Follow this Question
Related Questions
Rigidbody 2d rotation will count as float 0 Answers
How to rotate transform only on its Y axis? 1 Answer
What Should i use rigidbody.AddTorque() or Quaternions ? 1 Answer
How can I instantiate a gameobject facing another gameobject 2D? 0 Answers
Rotate Ball with high speed rotation to slow speed 2 Answers