Moving the Camera via scripting

Hello there.

So I’m trying to move the Main Camera around based on the position of the player character. In theory, every time the player moves the camera should follow them. In this case, the camera is tracking the character based on Z movement.

And while that part has been achieved, now I want to adjust the position of the camera within the script, in this case the Y position. This is so I don’t have to manually move the camera around in the editor and so I know exactly how many units are in relation to the original position. This is mostly preparation for a later part of the script where I want the camera’s position to be on a slight delay before moving with the player character, but for now I want to get this done as a test first.

So here, cameraYAdj is supposed to be the variable that alters the Y position. It’s set up under cameraYPos and is supposed to modify that. However, as is nothing happens and when I checked a couple of things, it seems like the Y coordinate of the camera isn’t moving as intended.

(other details: the script is currently attached to the camera and the character controller being used on the player character is the default platformer controller)

var playerCamera : GameObject; 
var cameraPos : Vector3;
var cameraYPos : float;
var cameraYAdj : int = 0;
var player : GameObject; 
var playerPos : Vector3; 
var currentPos : Vector3; 

function Start () {


function Update () { 
	cameraPos = playerCamera.transform.position;
	playerCamera.transform.position.z = player.transform.position.z;
	cameraYPos = playerCamera.transform.position.y + cameraYadj;
	playerPos = player.transform.position; 
	currentPos = playerPos; 
	//print("Player position:" +playerPos);
	//print("Current position:" +currentPos);
	print("Camera position:" +cameraPos);

It doesn’t seem like you are setting the Y camera position anymore after you set the Z position.

Right after line 16, you might want to add:

playerCamera.transform.position.y = cameraYPos;

To set the Y position.

You do not set the y-position of the camera back to its transform.

Just change your code like this:

 cameraPos = playerCamera.transform.position;
 playerCamera.transform.position.z = player.transform.position.z;
 cameraYPos = player.transform.position.y + cameraYadj;
 playerCamera.transform.position.y = cameraYPos;
 playerPos = player.transform.position;