Restrict the player from moving outside the camera’s view (screen) in Unity. - mohumohu studio

mohumohu studio

           

みずきの技術&読書ブログ&無料ゲーム

プロフィール画像

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

  1. Example Code Implementation
  2. Explanation
  3. Summary

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.

ClampPlayerToScreen() Implementation example


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件のコメント

コメントはまだありません。最初の一人になりましょう!

Leave a Reply

Your email address will not be published. Required fields are marked *