Moving Camera only when player crosses a point

I was thinking about making a platformer, but I don’t want the camera to move with player, I only want it to move, when player crosses the screen border, so you kinda get that feeling that you move between levels even though you are in the same location (examples : Zelda, Pokemon).

I tried to do this myself, wrote a small script, but my problem is that I still do not understand how to use Transform, transform and (G)(g)ameObject stuff.

Here’s the code itself

#pragma strict

	var player : Transform;
	var cam : GameObject;

	function Update () {

		if (player.position.x > Screen.width) {
		
			cam.transform.position.x += Screen.width;

		}
		if (player.position.x < -Screen.width) {
		
			cam.transform.position.x -= Screen.width;

		}

	}

Please help guys, that’s the only problem I’ve got so far

What you’re doing in principle works, but you’re just not updating the camera position properly. You can’t assign a value to it like any other variable, you have to assign a vector to it.

So instead of writing this:

cam.transform.position.x += Screen.width;

write this:

cam.transform.position = new Vector2 (cam.transform.position.x += Screen.width, cam.transform.position.y);

Depending on what you’re doing, you may need Vector3 rather than Vector2, in which case you’d need to specify the z-position too. There may be better ways to do it, but that’s the way that I know! :slight_smile:

Transform.position is in units and Screen.width is in pixels. Also Screen.width does not have a position somewhere.

You need to transform the right screen edge into world space:

if (player.position.x > Camera.main.ScreenToWorldPoint(new Vector3(Screen.width,0,0)).x) {
Vector3 newPos = Camera.main.transform.position;
newPos.x += Camera.ScreenToWorldPoint(new Vector3(Screen.width,0,0)).x;
Camera.main.transform.position = newPos;
}