LookAt to rotate only on Y axis?

// The target variable shows up as a property in the inspector. 
// Drag another object onto it to make the camera look at it.
var target : Transform; 

// Rotate the unit every frame so it keeps looking at the target 
function Update() {
    transform.LookAt(target);
}

It must be simple but it is me after all … :sweat_smile:

How do I make this transform happen only in the Y-axis, so that the object it’s attached to only rotates around the Y axis to look at the target?
Gracias.

function Update() {
    transform.LookAt(target.position.x, transform.position.y, target.position.z);
}

Though, you’ll probably want to cache your local transform.

1 Like

Wow burnumd, that’s elegant code. I’m going to use that in the future. Thanks for posting!

Thanks much! I will tackle when I get home and get my laptop plugged back in again. 9% battery right now.

Nope … no luck … this is the error …

No appropriate version of ‘UnityEngine.Transform.LookAt’ for the argument list ‘(float, float, float)’ was found.

You’d need to send the positions as a single vector3 i believe.

In that case, you should be able to simply provide it the transform.position and it should be good.

1 Like

transform.LookAt(Vector3(target.position.x, transform.position.y, target.position.z));

Thanks, that fixed it.

1 Like

Aren’t transform.position a Vector3?

So you should be able to write

transform.LookAt(target.position);

No it’s a Quaternion… Haha just joking. Your code will billboard all the axes, and that’s not what he wants (Read the title).

Actually this DOES work and rotates only on Y.

Reading Carefully (^_^) the code isn’t (target, target, target), it’s (target, THISTRANSFROM, target) which is why it works.

The summation of the code should be:

var thisTransform : Transform;
var target : Transform;

function Start/Awake () {
  thisTransform = this.Transform;
}

function Update() { 
    thisTransform.LookAt(Vector3(target.position.x, thisTransform.position.y, target.position.z));
}

What I’m finding with this code, is that is seems to monkey with the physics of the object that’s using it, but this is probably an issue with LookAt(), rather than ignoring the Y.