ClampToScreen() : Keep Unity objects within screen bounds

A Unity script to clamp your game objects within the screen bounds

Keeping game objects in view at all times is often a problem in Unity 2D games. However with this easy to use C# Unity method you simply have to pass in the object and give it some padding values and it takes care of the rest.

I have used this method, or variations of it in many of my 2D Unity projects. To use it add it to you objects controller script and then call it from the update method.

The padding parameters allow you to keep your game object fully in view using this method. Without padding (setting the p values to zero) will cause the game object to push half its width or height out of the screen, Depending on if its at the top or bottom of the screen.

The code

Add this to any script on your object and then call within the Update or LateUpdate method and that is!! Enjoy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
/// <summary>
/// Method to clamp a given transform to within the screend bounds.
/// </summary>
/// <param name="clampTransform">The transform you wish to clamp</param>
/// <param name="pLeft">The width of the left side padding</param>
/// <param name="pRight">The width of the right side padding</param>
/// <param name="pTop">The width of paddding at the top of the screen</param>
/// <param name="pBottom">The width of the padding at the bottom o the screen</param>
void ClampToScreen(Transform clampTransform, float pLeft, float pRight, float pTop, float pBottom)
{
    // Get the screen position of the object to clamp
    Vector3 ScreenPosition = Camera.main.WorldToViewportPoint(clampTransform.position);
    // Clamp the horizontal position 
    ScreenPosition.x = Mathf.Clamp(ScreenPosition.x, pLeft, 1f - pRight);
    // Clamp the vertical position
    ScreenPosition.y = Mathf.Clamp(ScreenPosition.y, pBottom, 1f - pTop);
    // set the clamped position back to the transform
    clampTransform.position = Camera.main.ViewportToWorldPoint(ScreenPosition);
}

If you are interested in checking out more of my simple Unity code solutions you can find them by clicking HERE.