I need some help figuring out how to program a camera in 2D.
I have a few questions:
- How do I get the camera to stop moving when it reaches the end of the screen (or the end of the background sprite)?
- I only want the Camera to follow the player when the player reaches the middle of the screen (so the camera will remain stationary while the player is on either side of the screen, but once the player starts walking left or right, the camera follows them after they reach the middle of the camera)
- Same question as #2 but moving vertically up or down screen.
I should mention that this is a platformer. Also in C#.
Any help or suggestions would be greatly appreciated.
Thanks!
Hi !
First of all, to do this properly, make sure your camera and your character are not linked in the scene hierarchy : by moving them together via script, you’ll be sure to control everything. Otherwise there will be a few cases where you’ll want to prevent the camera from moving by itself, and it is harder if one is the parent of another.
Then :
-
Use invisible markups (i.e. Transforms of empty GameObjects) to indicate your side limits. Then, in the script where you handle your camera movement, you only execute this movement after having checked your camera position.
-
Since the middle of the screen also happens to be your cameras’s transform.position.x, you can add one more constraint to your camera behaviour : if your player moves to the right, you only move your camera when the player’s position.x is greater or equal to the camera’s position.x.
And vice versa if the player moves left.
-
On the Y-axis the configuration is the same, but the threshold you’ll want to use for moving the camera is not necessarily at 50% of the screen (otherwise the character will be too high and it will look weird). So, you can once again use an invisible markup that you will check instead of the camera’s position. Since its position must be always relative to the camera, this one has to be a child of the camera.