Unity 3D Game Engine – JS Script – Follow the Player & Indipendent LookAt

1. Hierarchy> Create the structure:

– Player (the GameObject the Camera Group will follow)

– CameraGroup (Empty Object) -> father
— CameraTarget (Empty Object) -> child
— Main Camera -> child

2. ‘CameraGroup’ Object assign ‘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;
}

Inspector> CameraGroup> LookAt.js> Assign to var GameObject-> Player Object

3. ‘Main Camera’ Object assign ‘LookAt.js’


#pragma strict

// #################################################################################################
// This complete script can be attached to a camera to make it continuously point at another object.
// ################################################################################################# 

// Camera target public variable START #############################################################
// The target variable shows up as a property in the inspector. Drag another object onto it to make the camera look at it.
var cameraTarget : Transform;
// Camera target public variable END ###############################################################

function Start () {

}
	
function Update() {
	
}
	
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.
transform.LookAt(cameraTarget);
}

Inspector> Main Camera> LookAt.js> Assign to var cameraTargett-> CameraTarget Object

4. PLAY> while playing… Inspector> change Player’s position and CameraTarget’s position