Super simple Unity script in Javascript Camera follow perfect for 2D Platform game

Published in New

  camera follow in unity screenshot
Here is a tiny script which will allow you to add a camera follow to create a simple 2D platform game like Super Mario.


I have posted this for those looking for a Camera follow script for a 2D game, but you may not need to add a script.

The easiest way to follow an object if you are making a 2D platform game is to simply make the camera a child of the object you want to follow. To do this simply drag the camera on top of the object you want it to follow (in the Hierarchy pane of Unity).

If what you were looking for is a Javascript that makes a simple camera flow for 2D Platform games (if you don't know how to add a script, it's explained lower down.):

var target : GameObject;
var zposition : float;
var ypos
ition : float;

function Update()
{
transform.position.y = target.transform.position.y;
transform.position.x = target.transform.position.x;
transform.position.z = zpos
ition;
transform.position.y = ypos
ition;
}


How to install:

  • Right click Unity's Project pane and click "create" > "Javascript". This will create a blank Javascript file. Name it something like: "simplecamerafollow"
  • Now double click it to launch it in the Mono Develop code editor
  • Copy and past the code from above
  • Save the file and return to Unity
  • Drag and drop your newly created camera follow script onto the camera in your scene (drag it from the project pane onto the name of the camera in the Hierarchy pane)
  • Now click the camera in the hierarchy pane and you can see that in Inspector pane the camera follow script now appear at the bottom of the camera information.
  • Drag the object you want to follow from the Heirachy pane to the parameter "target" in the script information at the bottom of the inspector pane.
  • You should edit the values of "zposition" and "yposition" to position your camera. You will probably need a negative value (-10 etc) if the character of your 2D platform game is located at z=0.


The camera should nicely follow you character as it moves along the X axis making a smooth simple camera follow for a 2D platform game.

Notes:
If you character is going to move a great distance up or down (the y axis) you should remove the lines:

var yposition : float;
transform.position.y = yposition;


These allowed you to set a y height from within the inspector in Unity which will not change. It is entirely possible your character might exit the camera if it goes to high or too low in your 2D Platform unity game. With those lines deleted the camera will also follow the character in the y axis.