Search code examples
actionscript-3flashmovieclip

AS3: detecting movieclip in radius


I am developing a tree game and having dots to add branches on the tree, I want to enhance it for e.g. when one dot get a click then it display other dots within a particular radius around it.


Solution

  • From the description you've given, I think you are looking for Distance Formula.

    Sqrt((y2-y1)^2 + (x2-x1)^2)

    For example:

    You have a radius defined and an array of dots:

    var radius:int = 20;
    var myDots = new Array ({'x':0, 'y': 0}, {'x': 5, 'y': 5}, {'x': 10, 'y': 5}, {'x': 10, 'y': 5}, {'x': 10, 'y': 10});
    

    The dot being clicked is (5,5) and suppose you have a determined radius r=20. Now, to get all the dots withing the radius r, by iterating in the dots:

        function getDotsWithinRadius(x,y){
            for(var i= 0; i<myDots.length;i++){
                var x2 = myDots[i].x;
                var y2 = myDots[i].y;
                var val = Math.sqrt(Math.pow(y2-y,2) + Math.pow(x2-x, 2)); 
                if(val <=radious){
                   /*The dot is with the radius of the give location.
                     This is the place where you tell the current dot to show up or
                     something like that.
                    */
                }
            }
        }
    

    I haven't tested the code but I really hope this gives you an understanding.