- Home /
Limiting Game Object position by rect
Hello! What is the best solution for limiting 2D GameObject by rect? I know that I can check if its inside of rect or not, but how to make like shown in the picture below? Looking for a solution, that it would always stay on edge, no matter what coordinates it has, and update it even when it is outside rectangle, not just simply stop. Something similar to mobile joystick, but with rectangle.
Comment
Best Answer
Answer by robertbu · Feb 06, 2014 at 04:45 PM
Assuming the blue square is the mouse, the camera is Orthograpic, and that xMin, xMax, yMin, and yMax are world coordinates, then you can do:
#pragma strict
var yMin = -2.0;
var yMax = 2.5;
var xMin = -3.0;
var xMax = 3.25;
function Update () {
var pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
pos.z = transform.position.z;
pos.x = Mathf.Clamp(pos.x, xMin, xMax);
pos.y = Mathf.Clamp(pos.y, yMin, yMax);
transform.position = pos;
}
I thinked that it supposed to do something with $$anonymous$$athf.Clamp but your example is easier than I thought! Thank you!
Your answer
