- Home /
Making a specific axis look at an object
How can i get something to look at something but just on one axis, such as the y axis, so the object is always looking at an object but never looking up or down, just left and right, always following the object. I tried this code and it didnt work:
var PlayerObj : Transform;
function Update () {
transform.rotation.y.LookAt(PlayerObj);
}
Please help!
Answer by flokkienathur · Aug 26, 2012 at 06:04 AM
You could try to make 2 vector3's with the same x and z position and than use the LookAt function on Quaternion. Than it will rotate on only the y axis. Or you could make a new quaternion, set it equal to the current rotation, then rotate the object and reset everything in the wuaternion exept for the y rotation. Only problem is, quaterions are realy difficult to understand so if you use the second method, and you run into a problem, try the first :)
Hope this helps!
Yeah, im kind of a noob. I understand many things, but i never seemed to understand Quaternions. $$anonymous$$ind giving me an example based on my script thats in the post?
He means something like this:
function Update(){ var pos = target.position; // get the target position... pos.y = transform.y; // but at this object's height transform.LookAt(pos); // then look at it }
Answer by ScroodgeM · Aug 26, 2012 at 08:57 PM
C#
using UnityEngine; using System.Collections; public class Yrotater : MonoBehaviour { public Transform lookAt; void Update() { Vector3 worldLookDirection = lookAt.position - transform.position; Vector3 localLookDirection = transform.InverseTransformDirection(worldLookDirection); localLookDirection.y = 0; transform.forward = transform.rotation * localLookDirection; } }
Well, i will see what i can do with this. I dont code in C# so i dont know what the first 3 lines mean, but i believe i understand the rest. I will approve your answer if it ends up being correct.
In UnityScript:
function Update(){ var worldLookDirection = lookAt.position - transform.position; var localLookDirection = transform.InverseTransformDirection(worldLookDirection); localLookDirection.y = 0; transform.forward = transform.rotation * localLookDirection; }This is a more complete case, where the object will rotate strictly around its local Y axis (even if its inclined relative to the world Y axis). $$anonymous$$ore often, the object must simply rotate around the world Y axis, which simplifies things:
function Update(){ var lookDirection = lookAt.position - transform.position; lookDirection.y = 0; transform.forward = transform.rotation * lookDirection; }
Your answer
Follow this Question
Related Questions
LookAt on one axis 2 Answers
How can I rotate towards/look at a specific axis of a collided object? 2 Answers
Object facing the wrong way? 1 Answer
LookAt() with X axis 1 Answer
[Please!] Noob need's help with planet gravity movement. 2 Answers