How to make a circle on a grid?

2020-02-28 04:01发布

问题:

I'm making a game where all movement is grid based. I also wan't to make entities that can travel around in a circle. So does anyone have any suggestions for creating a circle out of a grid of squares (like the way MS Paint uses the circle tool to make a circle out of square pixels).

回答1:

Check out Midpoint circle algorithm.



回答2:

Here is my Java implementation of Bresenham's Midpoint Circle algorithm:

private void drawCircle(final int centerX, final int centerY, final int radius) {
    int d = 3 - (2 * radius);
    int x = 0;
    int y = radius;
    Color circleColor = Color.white;

    do {
        image.setPixel(centerX + x, centerY + y, circleColor);
        image.setPixel(centerX + x, centerY - y, circleColor);
        image.setPixel(centerX - x, centerY + y, circleColor);
        image.setPixel(centerX - x, centerY - y, circleColor);
        image.setPixel(centerX + y, centerY + x, circleColor);
        image.setPixel(centerX + y, centerY - x, circleColor);
        image.setPixel(centerX - y, centerY + x, circleColor);
        image.setPixel(centerX - y, centerY - x, circleColor);
        if (d < 0) {
            d = d + (4 * x) + 6;
        } else {
            d = d + 4 * (x - y) + 10;
            y--;
        }
        x++;
    } while (x <= y);
}

The full class implementation and many other language examples can be found on the Rosetta Code site.