0
\$\begingroup\$

In my scene I have two cubes one has a tag "Respawn" and another one has the following script attached:

using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

    void Update () {
        transform.rotation = Quaternion.LookRotation (
            GameObject.FindGameObjectWithTag("Respawn").transform.position
        );
    }
}

When I run it and move around my second cube with "Respawn" tag the first cube doesn't always looks at it, at certain point it just starts rotating the opposite side as if it has bounds to it's rotation. What am I doing wrong?

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Not a unity expert, so I'm not posting as a for-sure answer... but does LookRotation need to be relative? like Quaternion.LookRotation( otherObject.transform.position - this.transform.position) ? \$\endgroup\$ Commented Sep 5, 2015 at 17:46
  • \$\begingroup\$ Thanx that helped \$\endgroup\$
    – John Smith
    Commented Sep 7, 2015 at 14:40
  • \$\begingroup\$ @VadimTatarnikov Also dont use GameObject.FindGameObjectWithTag in an update method. You can just find it on Start() or every time it gets removed/instantiated, its not necessary to find it every frame \$\endgroup\$
    – Nick
    Commented Mar 25, 2020 at 17:50

1 Answer 1

1
\$\begingroup\$

Instead of using Quaternion.LookRotation, use this instead:

transform.LookAt(GameObject.FindGameObjectWithTag("Respawn").transform.position);

This will automatically rotate the object to look at the desired position, which in this case is the position of the Respawn object.

I would also really recommend storing the Respawn object as a variable instead of searching for it every frame.

EDIT: Ignore the stuff above. If you want to be able to use Quaternion.LookRotation so you can, for example, use Lerp or Slerp, you just have to make the position relative as david van brink pointed out, so it will look like this:

Vector3 diff = (GameObject.FindGameObjectWithTag("Respawn").transform.position) - transform.position;
transform.rotation = Quaternion.LookRotation (diff);
\$\endgroup\$
2
  • \$\begingroup\$ Yeah I tried it but the rotation is instant which isn't what I want \$\endgroup\$
    – John Smith
    Commented Sep 5, 2015 at 19:03
  • \$\begingroup\$ That's why I want to use quaternion.lookrotation() cause I can also use slerp after. \$\endgroup\$
    – John Smith
    Commented Sep 5, 2015 at 19:37

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .