Unity 3D Game Engine – JS Script – Follow the Player

1. MAIN TOP MENU> Game Object> Create Other> Cube> rename it ‘Player’

2. Hierarchy> Select ‘Main Camera’> Inspector> ‘Add Component’> New script> ‘CameraController.js’

CameraController.js:


#pragma strict
 
//The GameObject the Camera will follow 
public var player : GameObject;
//The actual Camera Position
private var offset :  Vector3;
 
function Start () {
offset = transform.position;
}
 
function LateUpdate () {
//LateUpdate is called after all Update functions have been called. 
// This is useful to order script execution. For example a follow camera should always be implemented in LateUpdate because it tracks objects that might have moved inside Update.
// The camera moves player.position+his own position
transform.position = player.transform.position + offset;
}

3. Hierarchy> ‘Main Camera’> Inspector> LookAt.js> DRAG ANd DROP over puiblic variable ‘Player’> the ‘Player’ object you have created at point 1.

4. PLAY the game, while playing from Inspector change ‘Player’ object position to see the final result.