- Home /
Fixed camera on rails.
Hello, I'm trying to find out how I can make a proper camera script. My camera needs to follow an object up, down, left and right. So it can only move on the X and Y axis. I also want to make it so there is a bit of feathering to it. I have looked through Unity Reference but I can't find it. Thank you! -Nelis
Answer by Khada · Mar 03, 2013 at 12:58 PM
You have to code this sort of thing manually and there are endless techniques that can be used to achieve varying results. Here's how to get the camera to follow an object on the X and Y axes to get you started.
//set this to the object to follow
public GameObject followObject;
//I recommend moving the camera in the LateUpdate method
void LateUpdate()
{
Vector3 camPos = Camera.main.transform.position;
camPos.x = followObject.transform.position.x;
camPos.y = followObject.transform.position.y;
Camera.main.transform.position = camPos;
}
EDIT: Attempted java version (I don't use java, there may be mistakes):
//set this to the object to follow
var followObject : GameObject;
//I recommend moving the camera in the LateUpdate method
function LateUpdate()
{
var camPos : Vector3 = Camera.main.transform.position;
camPos.x = followObject.transform.position.x;
camPos.y = followObject.transform.position.y;
Camera.main.transform.position = camPos;
}
I'm sorry, but it doesn't work. The camera doesn't move. I'm also getting a 'NullReferenceException: Object reference not set to an instance of an object'
As per the comment, you have to set 'followObject' to the object you want the camera to follow. You can do this via the inspector. It won't work unless you do this.
Answer by makegoalken · Mar 04, 2020 at 08:13 AM
Thank you very much for these great cake recipes, I have learned a lot from your web blog candy crush soda
Your answer

Follow this Question
Related Questions
Making my look script turn smoothly 0 Answers
Move RigidBody character relative to camera. 2 Answers
Smooth Camera Follow Script, Weird Movement... Please help! 1 Answer
Having Trouble animating camera at start of game 1 Answer
how to stop the camera to follow the player on his jump movement ? 2 Answers