Search Unity

Set Rotation with LookAt and Quaternion

Discussion in 'Scripting' started by kai_226, Nov 24, 2017.

  1. kai_226

    kai_226

    Joined:
    Jul 6, 2017
    Posts:
    53
    Hey guys, I want to rotate an Object instantly. The Y and Z axis should rotate so the Object looks at GameObject A while the X axis should be taken from the X axis rotation of GameObject B.

    I thought about doing something like this:
    Code (CSharp):
    1. transform.LookAt(GameObjectA.transform);
    2. myRigidbody.rotation = Quaternion.Euler(GameObjectB.rotation.x, myRigidbody.rotation.y, myRigidbody.rotation.z);

    But it always ends up with the rotation of Object B on all three axis.
    Any ideas?

    Thanks!
     
  2. Kaart

    Kaart

    Joined:
    Jul 31, 2017
    Posts:
    62
    Use transform.LookAt like you did in your code and then set the x-rotation with transform.eulerAngles.

    Code (CSharp):
    1. public class LookAt : MonoBehaviour {
    2.     public GameObject objectA;
    3.     public GameObject objectB;
    4.  
    5.     // Use this for initialization
    6.     void Start () {
    7.         transform.LookAt(objectA.transform);
    8.  
    9.         Vector3 myRotation = transform.eulerAngles;
    10.         myRotation.x = objectB.transform.eulerAngles.x;
    11.         transform.eulerAngles = myRotation;
    12.  
    13.     }
    14. }
     
    kai_226 likes this.
  3. kai_226

    kai_226

    Joined:
    Jul 6, 2017
    Posts:
    53
    Thanks a bunch, man :)