- Home /
Getting the screen bounds on a perspective camera
Hello everyone,
I'm using a perspective camera to achieve my desired parallax effect for 2D game. My dialogue system places a given line of dialogue above the character object, updating its position as the object moves.
My problem: I'm trying to get the dialogue box to remain in the bounds of the screen if the character is not visible (e.g. if they are calling from a distance, off-screen). My solution has been to get the width and height of the screen and convert it to world units, then use those values to clamp the target position of the dialogue box so.
This is what happens: Behaviour example
The Y appears to work correctly, but the X position does not update. If I put in raw world unit numbers to clamp the x, it does work - which leads me to assume I'm not getting the screen width correctly. My code is below (the commented out section is the code which produces the behaviour linked above. The uncommented section is using the aforementioned raw numbers.)
Any pointers would be hugely appreciated. Thankyou!
void PositionCanvas()
{
if (character != null)
{
Vector2 screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z)); // Get the screen bounds in world units
Vector2 targetPosition = new Vector2(GetCharacterPosition().x, GetCharacterPosition().y + charHeight * dialogueBoxHeight); // The target canvas position above the character sprite
targetPosition.x = Mathf.Clamp(targetPosition.x, -2.4f, 2.4f);
targetPosition.y = Mathf.Clamp(targetPosition.y, screenBounds.y + objectSize.y, screenBounds.y * -1 - objectSize.y);
//targetPosition.x = Mathf.Clamp(targetPosition.x, screenBounds.x + objectSize.x, screenBounds.x * -1 - objectSize.x);
//targetPosition.y = Mathf.Clamp(targetPosition.y, screenBounds.y + objectSize.y, screenBounds.y * -1 - objectSize.y);
transform.position = targetPosition;
}
}
Your answer
Follow this Question
Related Questions
Diagonal camera limit 0 Answers
2D camera scaling 0 Answers
Unity 5 - 2d Instantiate at mouse position 1 Answer
When my Ortho camera zooms in, it distorts/warps my 2d tilemap. How do I fix this unwanted effect? 0 Answers
Cinemachine 2D Level Wrap 1 Answer