Search code examples
c++geometrytrigonometryangleclamp

(C++) Clamp 2D Position Within Circle (Drawn Using Midpoint Circle Algorithm)


I am currently drawing circles using the Midpoint Circle Algorithm in my C++ Program. Here is an example of the code I am using.

void drawcircle(int x0, int y0, int radius)
{
    int x = radius-1;
    int y = 0;
    int dx = 1;
    int dy = 1;
    int err = dx - (radius << 1);

    while (x >= y)
    {
        putpixel(x0 + x, y0 + y);
        putpixel(x0 + y, y0 + x);
        putpixel(x0 - y, y0 + x);
        putpixel(x0 - x, y0 + y);
        putpixel(x0 - x, y0 - y);
        putpixel(x0 - y, y0 - x);
        putpixel(x0 + y, y0 - x);
        putpixel(x0 + x, y0 - y);

        if (err <= 0)
        {
            y++;
            err += dy;
            dy += 2;
        }
        if (err > 0)
        {
            x--;
            dx += 2;
            err += (-radius << 1) + dx;
        }
    }
}

Now, my question is if I am drawing a circle like this drawcircle(100, 100, 100);, how could I take a 2D position and check whether that 2D position is within the circle, and if not, then return a 'clamped' 2D position on the edge of the circle.

This should help explain what I'm trying to accomplish a bit better.

void _2DPostionToCirclePosition(Vector2D in, Vector2D *out)
{
    //assume in = Vector2D(800, 1100)
    //here we somehow calculate if the in 2D
    //position is within the circle we
    //are drawing drawcircle(100, 100, 100).
    //if the in 2D vector is within the circle
    //just return in. but if it outside of the
    //circle calculate and return a clamped position
    //to the edge of the circle
    (*out).x = calculatedOutX;
    (*out).y = calculatedOutY;
}

Solution

  • To determine if a point is in the circle first you need to calculate it's distance from the center of the circle, which here you have (100,100). Something like this :

    #include <math.h> //for pow and sqrt
    
    double getPointDistance(int x, int y) {
        return sqrt (pow ((circleCenterX - x), 2.0) + 
            pow ((circleCenterY - y), 2.0));
    }
    

    Then you can just compare it to your circle radius, if distance is bigger than radius it's outside, if it's smaller it's inside and if it's equal then it's right on the edge. To do so you can use something like this :

    bool isInCircle(int x, int y) {
        if (circleRadius >= getPointDistance(x, y)) {
            //it's inside the circle (we assumed on the edge is inside)
            return true;
        } else {
            //given point is outside of the circle
            return false;
        }
    }