Beginner B19 – Following with LookAt()
How to make objects rotate to face other objects using the Transform class’s LookAt function.
Code Used (Javascript)
-
var myTransform : Transform;
-
-
function Update () {
-
-
transform.LookAt(myTransform);
-
-
}
Further Reading
12 Comments
Leave a Comment









Wow! Very nice!!! Thanks for sharing!
i need this for some scenes in my game.
cya!
I am a bit confused.
var myTransform : Transform;
which expect object type is “Transform”, but redbox is a gameObject.
How could the object type match?
Hi Rocky, basically the key point is at 1:00 where I say that the LookAt() command requires a Transform component – put simply the transform component of a particular object. What you should remember here is that all objects that exist have a Transform component and when data typing to something you can be specific about what type (what component an object has) to save computation – for example if you said -
var exampleThing : Rigidbody;
Then Unity would assume a game Object that has a rigidbody component, and that in your scripting you want to deal with rigidbody commands. Does that make a little more sense?
I see, wgstone. As redbox has component “Transform”, unity automatically go into object redbox to extract component “Tranform” for parameter.
I tried to modify it to use GameObject:
var myObject: GameObject;
function Update () {
transform.LookAt(myObject.transform);
}
It turns out that I was forced to use “tranform”, instead of “Transform”. Why?
Should component be started with uppercase or lowercase?
rocky,
‘Transform’ with the capital ‘T’ is a Class, just like ‘GameObject’ has a capital ‘G’
Is there a way to only look at the x or y axis?
Not directly but you could work around it by using eulerAngles to lock off the other axes, this example looks at the X axis only because it is rotating around Y only, using eulerAngles = 0 to cancel the other two –
var target : Transform;
function Update () {
transform.LookAt(target);
transform.eulerAngles.x=0;
transform.eulerAngles.z=0;
}
I am trying to use raycasting, transform.LookAt, Rigidbody.AddForce, and Input.GetKeyUp to make an object move where I click(on a terrain, but that doesn’t really matter… I know basically what I want to say, but I don’t know exactly how to say it. I am really confused because i have a script which i thought would work, but apparently it doesn’t. When making this script, i also encountered the issue that the object would start to flip on its nose when i clicked close to the object. This would be much appreciated!
Oh.. i’ll start using that euler angles script referenced above^^^
Show us the script using http://pasteit4me.com please!
Realy nice
My big problem is how to create an A.I car.
Nice learning modules, , need varios A.I tutorials, in my case an A.I car driving via waypoints etc…
wow!!! so cooooool~!