Unity 3D Game Engine – Camera – 2D Platform – Smooth Follow

1. Inside Hierarchy create the structure:

– Player (parent)
— CameraTarget (Empty Object) (child)

– Main Camera

2. Select ‘Main Camera’ and create ‘CameraController.js’

CameraController.js


#pragma strict
 
var cameraTarget : GameObject; // Inspector> Assign the Camera Target NON è il target della camera ma la posizione che vuole raggiungere la camera

var smoothTime : float = 0.1;              // Delay in seconds to follow Player
var cameraFollowX : boolean = true;        // Inspector> if is checked -> The Camera will follow X position of cameraTarget
var cameraFollowY : boolean = true;        // Inspector> if is checked -> The Camera will follow Y position of cameraTarget
var cameraFollowHeight : boolean = false;  // if true the Camera Y Position = cameraHeight
var cameraHeight : float = 2.5;            // cameraHeight
var velocity : Vector2;
private var thisTransform : Transform;    

function Start ()
{
  thisTransform = transform;
}

function Update () 
{

if (cameraFollowX) // if cameraFollowX = true = Inspector is checked
{
  thisTransform.position.x = Mathf.SmoothDamp (thisTransform.position.x, cameraTarget.transform.position.x, velocity.x, smoothTime);
}

if (cameraFollowY) // if cameraFollowY = true = Inspector is checked
{
  thisTransform.position.y = Mathf.SmoothDamp (thisTransform.position.y, cameraTarget.transform.position.y, velocity.y, smoothTime);
}

if (!cameraFollowY && cameraFollowHeight)     // if cameraFollowY = false = Inspector is unchecked AND cameraFollowHeight = true = Inspector is checked
{
  camera.transform.position.y = cameraHeight; // The Camera Y position = cameraHeight
}

}

Main Camera> Inspector> LookAt.js> DRAG AND DROP over:
– var Camera Target -> CameraTarget (Empty Object)
– var Player -> Player (Game Object)
– var Smoot Time -> Delay time to reach final position

a. Camera Follow X check | Camera Follow Y check | Camera Follow Height uncheck | Camera Height
-> follow X and Y of cameraTarget

b. Camera Follow X uncheck | Camera Follow Y check | Camera Follow Height uncheck | Camera Height
-> follow Y of cameraTargetr the X value is the current X position in the viewport

c. Camera Follow X check | Camera Follow Y uncheck | Camera Follow Height check | Camera Height
-> follow X of cameraTarget and Y Camera Height value