Game Development Reference
In-Depth Information
Within the Update() function, the Transform of the game object to which the script is attached, in this
case the Main Camera, is rotated so its forward vector position points at the cameraTarget 's position.
In the Inspector, assign the Sphere game object to the Camera Target property with the circle
selection button to the right of its field. Save and play. The camera follows the sphere as it falls
onto the cube, bounces across the plane, then falls away. The camera position doesn't change as it
follows the movement of the Sphere. Now try following the Cube instead.
Accessing Other Game Objects
You've used OnCollision() to make changes to either game object involved in a collision. You can
also write script for one game object to have an effect on any other game object. In this example,
when the Sphere game object strikes the Cube game object, your script will tell the Main Camera to
follow the Cube rather than the Sphere.
In the Project panel, create a new script with Create ➤ JavaScript and name it
ChangeCameraTarget. Double-click to open it in MonoDevelop and edit to the following:
#pragma strict
function OnCollisionEnter() {
var cameraScript : PointCamera = GameObject.Find("Main Camera").GetComponent(PointCamera);
cameraScript.cameraTarget = GameObject.Find("Cube").transform;
}
This code breaks down as follows:
(1) var cameraScript : PointCamera
Declares the cameraScript reference variable of type PointCamera, the script attached to the Main
Camera game object that directs it to follow the Sphere game object.
(2) = GameObject.Find("Main Camera").GetComponent(PointCamera);
The cameraScript variable was declared as a script reference. Since this script is attached to the
Sphere game object, you use the GameObject.Find function to find any object with the name Main
Camera. Then with dot notation, drill down to the Main Camera game object's PointCamera script
component to assign it to cameraScript .
(3) cameraScript.cameraTarget
Using dot notation to identify the cameraTarget public variable,
(4) = GameObject.Find("Cube").transform;
change the target of the Main Camera by assigning the Cube game object transform.
Save the script and attach it to the Sphere game object. Save the scene and playtest. The camera
follows the Sphere down, then on impact switches to following the Cube.
 
Search WWH ::




Custom Search