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.
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;
}