# How to limit the distance of a point?

I'm making an Angry Birds like game and I need to limit the distance that the user can pull back the slingshot, how do I do this?

Get the length of the vector from the slingshot to the mouse/finger/whatever.

If it's more than your allowed length then normalise the vector (to make its length 1) then multiply it by the maximum length.

Note, to avoid a square-root (costly operation) in the first bit compare the length squared with the max length squared.

// Get a vector from slingPos to targetPos
// (you may actually want the other way round in your game,
// as the angry object will be thrown towards the slingPos)
var orignalVector = targetPos - slingPos;
var originalLengthSq = originalVector.X * originalVector.X +
originalVector.Y * originalVector.Y;
if (originalLengthSq > maxLengthSq)
{
// I have already done the first bit of normalisation (getting the length squared)
// so we re-use that calculation.
var normalisedVector = originalVector / sqrt(orignalLengthSq);
originalVector = normalisedVector * maxLength;
}

• Works great, but if the projectile is higher than the slingshot it doesn't work. How can I make it so that it does work? Apr 18, 2012 at 16:20
• @Deza This vector calculation should do the same thing no matter what the orientation of the pair of points is. Are you sure it's not that you actually want it to do something different in that case? If so, you need to be more specific than “doesn't work”. Perhaps you could provide screenshots of the failure and/or a diagram illustrating the results you want? Apr 18, 2012 at 19:43