- Home /
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.
Answer by robertbu · Sep 27, 2014 at 06:36 PM
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.
Thanks a lot. Will gave this a try as soon as possible!
This method works great for my C# script. I ended up only needing the pos.x value, but it works on any resolution I have tested so far. Now to get my enemies and obstacles to follow this logic :) Thank you kindly, as I have been trying to figure out a sane way to resolve the multiple screen width differences for a while!