- Home /
2D platform game stop camera from moving once reach end of screen
I'm trying to create a 2d platform game were the camera moves from left to right. I want the camera to stop moving when it reaches the end of the level. I tried stopping the camera when it's greater than or equal to the coordinates that I need. And it works! But if I try my game on different monitors/resolutions you get black space at the end of the level. (It doesn't stop when I want it to stop.) So is there a way to, no matter the resolution of the screen, stop the camera from moving?
Thanks for your help! :D
Answer by robertbu · Jan 02, 2014 at 12:14 AM
With an orthographic camera, the orthographicSize is 1/2 of the vertical height the camera sees. You can calculate the half width with:
var halfWidth = Camera.main.orthographicSize * Screen.width / Screen.height;
The 'halfWidth' is how far (x axis) before the end of your level you need to stop.
I don't understand. Based on the camera size how does it know how long my level is?
It doesn't. This just allows you to calculate the position. Say your level ends when x = 120 (I don't know how you have your level define, so I cannot be more precise). You need to stop your camera when the camera's x position is 120 - halfWidth. So whatever is the maximum x value of your level, the camera will be stoped 'halfWidth' before that value.
So would it look something like this (2.12 would be the end of my map):
if(transform.position.x == 2.12 - halfWidth)
{
//stop cam
}
else
{
//$$anonymous$$ove cam
}
I don't know how you have your code structured. Your code as-is won't work because you are using a direct comparison, and the chance of the value landing exactly on 2.12 - halfWidth is small. What you could do is this:
if (transform.position.x > 2.12 - halfWidth) {
transform.position.x = 2.12 - halfWidth;
}
Another possibility is to just not move the camera if the future position is beyond the end value. Assu$$anonymous$$g you do some sort of calculation for the future position and assign it to 'pos' you could do:
if (pos <= 2.12 - halfWidth) {
transform.position = pos;
}
But the first one would always be true b/c lets say the transform.position.x = 1 well that is greater than 2.12-halfwidth b/c my halfWidth is 640. And then the camera is way off the screen.
Your answer
Follow this Question
Related Questions
Spawning mobs in a platformer game 0 Answers
I'm having trouble with my character when playing in unity, and when I build and run the game 0 Answers
Has anyone made a successful Pixel Perfect Camera script for platformer games? 2 Answers
Blur on first plane 0 Answers
Adjust camera for different screen sizes 0 Answers