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?

| improve this question | | | | |
\$\endgroup\$
  • 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\$ – david van brink Sep 5 '15 at 17:46
  • \$\begingroup\$ Thanx that helped \$\endgroup\$ – Vadim Tatarnikov Sep 7 '15 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 Mar 25 at 17:50
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);
| improve this answer | | | | |
\$\endgroup\$
  • \$\begingroup\$ Yeah I tried it but the rotation is instant which isn't what I want \$\endgroup\$ – Vadim Tatarnikov Sep 5 '15 at 19:03
  • \$\begingroup\$ That's why I want to use quaternion.lookrotation() cause I can also use slerp after. \$\endgroup\$ – Vadim Tatarnikov Sep 5 '15 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.