Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

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;
}
share|improve this answer
    
+1 You beat me to it. :) –  Jonathan Hobbs Apr 18 '12 at 7:03
    
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? –  Deza Apr 18 '12 at 16:20
1  
@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? –  Kevin Reid Apr 18 '12 at 19:43
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.