- Home /
Clamping object movement in circle
I've taken a look at other questions but I dont seem to find an answer that works for me. I am trying to limit the position of an object within a circle (2D), while setting the position of my object to be that of the mouse. I have this script so far, but for some reason it works only when my object is position at Vector2(0,0) if it is at any other position the effect is messed up.
mousePos = Camera.main.ScreenToWorldPoint(Vector2(Input.mousePosition.x, Input.mousePosition.y));
transform.position = mousePos;
var allowedPos = transform.position - initialPos;
var finalPos = Vector2.ClampMagnitude(allowedPos, 2);
transform.position.x = finalPos.x;
transform.position.y = finalPos.y;
What I am essentially trying to achieve is a movement similar to how birds are dragged in angry birds.
Answer by robertbu · Aug 05, 2014 at 05:30 PM
Try this:
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
var allowedPos = mousePos - initialPos;
allowedPos = Vector3.ClampMagnitude(allowedPos, 2.0);
transform.position = initialPos + allowedPos;
May have to make initialPos a Vector3 if is not already.
thank you very much sir for the solution you provided, it works with my vectors still set to vector2!
Thank you! So simple, yet so useful. Worked like a charm.