There are often situations where we want to make one object orient itself to look in the direction of some other object. Examples include enemies or gun turrets wanting to look at the player, or perhaps making the player start off looking at an object at a key point in the game, such as, after having been teleported or respawned to some location in the game.
This recipe builds upon the player-controlled cube Unity project you created in the previous recipe. So make a copy of that project, open it, and then follow the steps for this recipe.
To make one object "look-at" another object, perform the following steps:
Arrow
positioned at (2, 0.5, 2) and with scale (1, 1, 1).Sphere-small
, positioned at (2, 0.5, 2.5) and with scale (0.5, 0.5, 0.5).By default, when objects are first created, they are "looking" (facing) along the Z-axis. By positioning Sphere-small
at (0, 0, 0.5), we have made this smaller sphere the point of an arrow. In other words, when we look at the two spheres, they are facing in the direction of a line drawn from the center of the large sphere towards the center of the small sphere.
You can check whether this is correct in the Scene window. Selecting Arrow, you should see the blue Z-axis gizmo arrow point from the center of the larger sphere towards the center of the smaller sphere.
Sphere-small
a child-object of your GameObject Arrow
.To make an object a child of another object, in the Hierarchy window drag the child object into the parent object. The child object should then appear indented below the parent object. The parent object will also have a contents triangle symbol next to it, to control whether its contents (child objects) are listed or not.
Arrow
:// file: LookAt.cs using UnityEngine; using System.Collections; public class LookAt : MonoBehaviour { public Transform playerTransform; private void LateUpdate () { transform.LookAt( playerTransform ); UsefulFunctions.DebugRay(transform.position, transform.forward * 100, Color.green); } }
LookAt
scripted component, drag Cube-player over the public variable playerTransform.Since it is so useful, Unity has provided all Transform
objects with the LookAt()
method. This method will make the object whose transform has the method applied, orient itself at the object whose transform is provided as a parameter. Since our Arrow
object's script has a reference to Cube-player
(via the public variable playerTransform
), every frame the Arrow
object is made to re-orient itself to, faces towards the direction of the player's character.
The second statement in the LateUpdate()
method is the call to the DebugRay()
method of the UsefulFunctions
class. This illustrates that the "rays" (lines in 3D space) that can be drawn in the Scene window, and can aid in debugging. This statement will result in a ray being drawn in green, from the position of the Arrow object's transform, 100 Unity units in the direction the Arrow object is facing (its transform's forward
vector).
3.143.0.85