How to constrain movement within the area of a circle

前端 未结 4 1766
星月不相逢
星月不相逢 2020-12-03 19:27

This might be more a geometry related question, but I\'m trying to constrain a controller within an area of a circle. I know I have to touch the Math.sin() and Math.cos() me

4条回答
  •  庸人自扰
    2020-12-03 19:50

    This arithmetic is trivial as long as you normalize each data point (prospective position), which i have tried to do in the function below:

    function locatePoint(canvas_size, next_position) {
        // canvas_size & next_position are both 2-element arrays
        // (w, h) & (x, y)
        dist = function(x, y) {
            return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
        };
        x = next_position[0];
        y = next_position[1];
        rescaledX = x/(canvas_size[0]/2);
        rescaledY = y/(canvas_size[1]/2);
        if (distance(x, y) <= 1) {
        // the base case; position is w/in the circle
        } 
        else {
        // position is outside the circle, so perhaps
        // do something like random select a new position, then
        // call this function again (recursively) passing in 
        // that new position
        }   
    }
    

    so in the simple diagram below, i have just inscribed a unit circle (r=1) inside a square whose sides are r*2. Your canvas dimensions do not have to be square though. To further simplify the calculation, you only need to consider one of the four quadrants--the upper right quadrant, let's say. The reason is that the Euclidean distance formula squares each coordinate value, so negative values become positive.

    Put another way, the simplest way is to imagine a circle inscribed in your canvas and whose center is also the center of your canvas (so (0, 0) is the center not the upper left-hand corner); next, both canvas and circle are shrunk until the circle has radius = 1. Hopefully i have captured this in the function above.

    enter image description here

提交回复
热议问题