Finding all the points within a circle in 2D space

前端 未结 7 1779
自闭症患者
自闭症患者 2021-02-13 12:58

I am representing my 2D space (consider a window), where each pixel is shown as a cell in a 2D array. i.e. a 100x100 window is represented by the array of same dimensions.

7条回答
  •  误落风尘
    2021-02-13 14:00

    You can get speed ups by computing as much outside of the loops as possible. Also there's no need to do the Pythagoras Theorem square root... just keep everything squared. One final speed-up can be made by only doing the math for one quarter of the circle (because it's symmetrical)... when a match is found you just replicate it for the other three quarters.

    radiusSquared = radius*radius;
    rightEdge = centerX+radius;
    bottomEdge = centerY+radius;
    for(x = centerX; x <= rightEdge; x++){
        xSquared = x*x;
        for(y = centerY; y <= bottomEdge; y++){
            ySquared = y*y;
            distSquared = xSquared+ySquared;
            if(distSquared <= radiusSquared){
                // Get positions for the other quadrants.
                otherX = centerX-(x-centerX);
                otherY = centerY-(y-centerY);
                // Do something for all four quadrants.
                doSomething(x, y);
                doSomething(x, otherY);
                doSomething(otherX, y);
                doSomething(otherX, otherY);
            }
        }
    }
    

提交回复
热议问题