- Home /
How to get the camera's size in world units
Hello, I have a scripting problem I'm trying to get past. So, I want my camera in my 2D game to follow the player until he/she reaches the set right and left ends of the map, but I can't figure out how to get the proper property to do this. Here's the code I'm using:
// constant "RightWorldBoundary" = 35f; if (transform.position.x - camera. / 2 > Level.RightWorldBoundary) { return Level.RightWorldBoundary - camera. / 2; } // constant "LeftWorldBoundary" = -35f; else if (transform.position.x + camera. / 2 < Level.LeftWorldBoundary) { return Level.LeftWorldBoundary + camera. / 2; }
As another potentially useful note, I'm using a 16:9 ratio currently and I have a camera size of 10. What should I use in the __ space to get the width of the camera in world units and have the same type of measurement as my other factors like the transform.position?
// constant "RightWorldBoundary" = 35f;
if (transform.position.x - camera._______ / 2 > Level.RightWorldBoundary)
{
return Level.RightWorldBoundary - camera._______ / 2;
}
// constant "LeftWorldBoundary" = -35f;
else if (transform.position.x + camera._______ / 2 < Level.LeftWorldBoundary)
{
return Level.LeftWorldBoundary + camera._______ / 2;
}
Here's a clearer view of my code (hopfully! I'm kina new to this).
Answer by wb6089967 · Apr 22, 2021 at 06:51 PM
Okay, I've got it now. So, the "Size" property of the camera represents half of the camera's height in world units. this is accessed by using camera.orthographicSize the height is already halved for you, so that's not something you need to do. to convert from half the height to half the width, you just need to multiply camera.orthographicSize by camera.aspect, as I've done here:
camera = UnityEngine.Camera.main;
halfViewport = (camera.orthographicSize * camera.aspect);
here are the following edits I've made to my code with this in mind:
private float WorldBourdaryReached()
{
float playerXPosition = player.transform.position.x;
Debug.Log(playerXPosition);
if (playerXPosition + halfViewport >= Level.RightWorldBoundary)
{
return Level.RightWorldBoundary - halfViewport;
}
else if (playerXPosition - halfViewport <= Level.LeftWorldBoundary)
{
return Level.LeftWorldBoundary + halfViewport;
}
else
return 0f;
}
In my main update method, if the return of this is 0 (the last statement), I'll just use the player's x position as the camera's x, but if the return is anything but 0 (which will be the maximum the camera can move in either direction), I set the camera's x to the return value.
Your answer
Follow this Question
Related Questions
Smooth camera script looking at left hand side of character. 0 Answers
Rotatearaound a moving object 1 Answer
Problems with Gyroscope VR Car Game 0 Answers
How to adjust camera position/rotation when player looks up or down? (Third Person Camera) 1 Answer
"Follow Target" script with a prefab (C#) Help me please! 1 Answer