- Home /
Get a single number for rotation (2d game) when using Quaternion.FromToRotation
Im making a 2D game and have a rotation handler that only takes in one number (the z rotation) in as an input.
Vector3 dir = (Quaternion.FromToRotation(-transform.up, Target.position - transform.position) * transform.rotation).eulerAngles; Rotation = dir.z; I can't seem to get it to work nicely with Quaternion.FromToRotation() as it eventually outputs stuff on the x/y rotation and sets the z to something absurd like 237 ->122 (with 180 on the y) Is there a way i can convert these other angles to a one number rotation of the z axis?
Answer by Bunny83 · Jun 05 at 08:42 AM
Well, as long as your direction vectors only live in the x-y plane you should only get a single rotation around z. However since you do Target.position - transform.position
those two positions may not be at the same z position and therefore result in a diagonal vector which would give you a skewed result. Likewise if transform.up
is not a pure 2d "x-y" vector you can similar issues.
Anyways you shouldn't really use FromToRotation and then using the eulerAngle property in such a case as the resulting angle could always flip 180° since you're dealing with a quaternion. A quaternion is a "single rotation value", however all 4 components belong together. Converting this to euler angles.
It seems you just want to rotate the object so its up vector points towards the target? If that's the case you should be able to just do
transform.up = (Vector2)(Target.position - transform.position);
The Vector2 cast makes sure there's no z component in the direction vector. An alternative would be
transform.rotation = Quaternion.LookRotation(Vector3.forward, (Vector2)(Target.position - transform.position));