Restrict the player from moving outside the camera’s view (screen) in Unity.
Hello!!
This time, I’d like to give a brief explanation of how to prevent the player from going outside the camera’s view (screen) in Unity, based on a method I used in the shooting game I’m currently developing!
Table of Contents
Example Code Implementation
Clamp based on the camera’s viewport
Inside the Update()
method, add code to constrain the player’s position within the camera’s world space boundaries.
void Update()
{
ClampPlayerToScreen(); // ←Additional code
}
ClampPlayerToScreen() Implementation example
private void ClampPlayerToScreen()
{
Vector3 viewPos = Camera.main.WorldToViewportPoint(transform.position);
// Clamp so that it does not exceed the viewport range (0 to 1).
viewPos.x = Mathf.Clamp(viewPos.x, 0.05f, 0.95f); // Leave a small margin on the inside.
viewPos.y = Mathf.Clamp(viewPos.y, 0.05f, 0.95f);
// Convert the viewport coordinates back to world coordinates and update the position.
transform.position = Camera.main.ViewportToWorldPoint(viewPos);
}
Explanation
Why use Viewport?
- Viewport works with relative positions on the screen (from 0 to 1), so it allows consistent control regardless of resolution or aspect ratio.
- By using
Mathf.Clamp
, you can prevent the object from going off-screen.
Note
- This method also works when the camera is moving.
- Adjust the
Mathf.Clamp()
range (e.g., 0.05f to 0.95f) according to the character’s size.
Supplement
If the camera is fixed and does not follow the player, you can use something like Camera.main.ViewportToWorldPoint(new Vector3(0, 0, 0))
to get the world coordinates of the screen edges and use them as the min and max values for clamping.
Summary
In this article, I explained how to restrict the player from going outside the camera’s projection bounds (screen) in Unity!
I was amazed at how easily it can be implemented, so I wanted to share it with you!
Wishing you a great Unity development journey!
2025-06-19
0件のコメント
コメントはまだありません。最初の一人になりましょう!