Limit Movement of Object Based on Screen Size Unity2D

Hi, Bradley Here.

I am currently working on a 2D Unity game. I was wondering how you would limit the movement of an object to a certain point based on the screen size.

For example stop an object when it reaches the edge of the screen.

Cheers, Bradley.

Given an Orthographic camera, you can clamp the pivot point of an object to the screen by:

var pos = Camera.main.WorldToViewportPoint(transform.position);
pos.x = Mathf.Clamp01(pos.x);
pos.y = Mathf.Clamp01(pos.y);
transform.position = Camera.main.ViewportToWorldPoint(pos);

Viewport points go from (0,0) in the lower left corner to (1,1) in the upper right. So you can move the object more inside the visible window by changing the range:

var pos = Camera.main.WorldToViewportPoint(transform.position);
pos.x = Mathf.Clamp(pos.x, 0.07, 0.93);
pos.y = Mathf.Clamp(pos.y, 0.07, 0.03);
transform.position = Camera.main.ViewportToWorldPoint(pos);

To make sure the entire object no matter what it size and scale is fully visible in a potentially changing screen is a much more difficult problem.