- Home /
The question is answered, right answer was accepted
Rotate object around local Z axis
Hi! So, I'm trying to rotate a gameobject around the local Z axis to face another gameobject, and have the X and Y axis stay the same. But it always turns out weird. I have tried
Vector3 a = new Vector3 (target.position.x, target.position.y, target.position.z);
Vector3 b = new Vector3 (transform.position.x, transform.position.y, transform.position.z);
Vector3 direction = a - b;
direction.Normalize ();
Quaternion rotation = Quaternion.Euler(45f, -45f, Mathf.Atan2(direction.x, direction.y) * 57.29578f - 180f);
transform.rotation = rotation;
But, it only accounts for the X position of the two gameobjects. So when you're above the object, it will face down and when you're below the object, it will face up. I have also tried
Vector3 a = new Vector3 (target.position.x, target.position.y, target.position.z);
Vector3 b = new Vector3 (transform.position.x, transform.position.y, transform.position.z);
Vector3 direction = a - b;
Quaternion rotation = Quaternion.LookRotation (direction);
transform.rotation = rotation;
But, it rotates the object on all 3 axis. And if I change it to
transform.rotation.z = rotation.z;
It returns a
"Cannot modify a value type return value of 'UnityEngine.Transform.rotation'. Consider storing the value in a temporary variable"
error. I have also tried various other things, such as
float angleRad = Mathf.Atan2 (target.transform.position.y - transform.position.y, target.position.x - transform.position.x);
float angleDeg = (180 / Mathf.PI) * angleRad;
transform.rotation = Quaternion.Euler (45f, -45f, angleDeg);
And
transform.Rotate (new Vector3(45f, -45f, Quaternion.Euler(direction).z),Space.Self);
But they all have their own issues. So if anyone can help me solve this problem, that would be much appreciated. Thanks!
I think you need to use transfrom.localRotation ins$$anonymous$$d of transform.rotation.
Answer by nihohit1 · Oct 31, 2017 at 06:43 AM
Try using your own x & y coordinates while rotating:
Vector3 a = new Vector3 (transform.position.x, transform.position.y, target.position.z);
Vector3 b = new Vector3 (transform.position.x, transform.position.y, transform.position.z);
Vector3 direction = a - b;
Quaternion rotation = Quaternion.LookRotation (direction);
transform.rotation = rotation;
This won't work. Because in "a" and "b" vectors, x and y angles are the same. So in direction it will always be 0 and "transform rotation" will only return (0,0,0) or (0,0,180). Correct me if I have done something wrong.