usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Detecting the Region Demarcated by an Ellipse in C++ | usingMaths



Understanding the Ellipse Region | Maths Explanation for C++ Kids

In this tutorial, we'll learn how to use C++ ellipse region detection to determine whether a point or object lies inside a defined ellipse boundary. This concept combines two important ideas: geometry (the equation of an ellipse) and programming logic (using conditions in C++).

Being able to test if a point lies within an ellipse is useful in many areas — such as collision detection, interactive graphics, and educational simulations. Let's break it down step by step.


Checking the Boundaries of an Ellipse in C++ | The Mathematics Behind the Ellipse

We'll use the standard ellipse equation to calculate if an (x, y) coordinate is within the ellipse region in C++.

As explained in the Equation of an Ellipse in C++ tutorial, an ellipse centered at (h, k) with semi-major axis a and semi-minor axis b is defined by:

(x - h)2   +   (y - k)2   =   1
a2 b2

Every point (x, y) that satisfies this equation lies on the boundary of the ellipse. If the sum on the left-hand side is less than 1, then the point is inside the ellipse. If it's greater than 1, the point lies outside.

It can be deduced that y = k ± b/a√(a2 - (x - h)2) ;
And conversely x = h ± a/b√(b2 - (y - k)2)
Hence, the boundaries of any ellipse lie in the range
y ≥ k - b/a√(a2 - (xexternal - h)2);
y ≤ k + b/a√(a2 - (xexternal - h)2)
               and
x ≥ h - a/b√(b2 - (yexternal - k)2);
x ≤ h + a/b√(b2 - (yexternal - k)2)


Tip: The equation (x - h)² / a² + (y - k)² ≤ 1 defines the entire region of the ellipse, not just its outline.

Step-by-Step Explanation for C++ Algorithm

  • Use the ellipse equation to test points.
  • Apply the test to detect when an object enters the ellipse region.
  • Visualize the region on the C++ window frame.

Code to Detect Entrance into an Elliptical Region in C++

Any point (x, y) that satisfies (x - h)² / a² + (y - k)² ≤ 1 lies inside the ellipse region. We'll translate this into C++ code to perform region detection.

To check for when a second body enters the ellipse, we will continually use the x position of this second body in the ellipse equation to detect when its y position lies between the top and bottom limits at the x position in question:
y2nd_img(top) > k - b/a√(a2 - (x2nd_img - h)2)
and y2nd_img(bottom) < k + b/a√(a2 - (x2nd_img - h)2)
;
At the same time, we will use the y position of the second body in the ellipse equation to detect when its x position lies between the left and right limits at the y position in question:
x2nd_img(left) > h - a/b√(b2 - (y2nd_img - k)2)
and x2nd_img(right) < h + a/b√(b2 - (y2nd_img - k)2)

C++ elliptical region detection example on C++ window frame
Figure: C++ elliptical region detection example on C++ window frame

Here's a C++ code for ellipse region check using the C++ window frame element. This approach works well for ellipse region collision detection in graphics or games.

Create a new C++ project; call it Dymetric.
Create 2 new C++ class files;
Call them Facet and EllipticalRegion.
Type out the adjoining C++ code for detecting the instance a travelling body crosses the boundary of an ellipse.


By The Way: Notice how the equations for a circle are similar to those of an ellipse;
No surprise there!
A circle is just an ellipse in its simplest form.



How the C++ Elliptical Region Detection Code Works

  1. The ellipse is centered at (h, k) with radii a (horizontal) and b (vertical).
  2. For each point (x, y), we calculate ((x - h)² / a²) + ((y - k)² / b²).
  3. If the result is less than or equal to 1, the point lies inside the elliptical region.
  4. Otherwise, it is outside the region.

This same principle is used in collision detection algorithms for games and simulations, where objects have elliptical or circular boundaries.

Applications of Ellipse Region Logic

  • Graphics and Animation: Detecting when a sprite enters an elliptical area on the canvas.
  • Mathematics Education: Demonstrating geometric regions and inequalities involving ellipses.
  • Game Development: Checking collisions or hitboxes shaped like ellipses instead of rectangles.
  • Data Visualization: Highlighting focus zones or interactive selections shaped as ellipses.

In all these cases, C++ ellipse detection helps make interfaces interactive and geometrically accurate.


Key Takeaways on Elliptical Region Detection in C++

In this tutorial, you've learned:

  • The equation of an ellipse and how to test point positions,
  • How to use C++ and C++ window frame to visualize the region,
  • Practical applications of ellipse region detection in programming and mathematics.

Using C++ ellipse boundary code, we can check if a moving object or point enters the defined elliptical region. This method is useful in maths programming and interactive learning for senior secondary students.

This simple concept links algebra, geometry, and coding — showing how mathematics powers real programming!

Summary: Visualizing Elliptical Region in C++

In this tutorial, we learned how to perform ellipse boundary detection in C++. By using the standard ellipse equation, you can efficiently determine whether a point lies inside or outside the elliptical region. This logic is widely used in collision detection, interactive graphics, and data visualization.



So! C++ Fun Practice Exercise - Detect Elliptical Region

As a fun practice exercise, try implementing the same C++ code but using the parmetric equation of an ellipse this time. This will really validate your understanding of coordinate geometry interpretation and C++ graphical programming for ellipse region detection and mathematics application.







C++ Elliptical Boundary Dymetric Window Code Stub


C++ Elliptical Boundary Canvas Frame and Button Controls - Header File

#pragma once

class Facet
{
public:
    Facet(HWNDintint);
    virtual ~Facet();
    bool decorateButton(WPARAMLPARAM);
    bool actionPerformed(HWNDWPARAMLPARAM);
    void informPaint();
};


C++ Elliptical Boundary Canvas Frame and Button Controls - Class File

#include "stdafx.h"
#include "Facet.h"
#include "EllipticalRegion.h"

EllipticalRegion* elp_region;

/*
* Our custom class that interfaces between the parent window
* and the subsequent daemonstrator classes
*/

Facet::Facet(HWND hWndint window_widthint window_height)
{
    elp_region = new EllipticalRegion(hWndwindow_widthwindow_height);
}


/*
* This guy decorates buttons with colour and title text
*/

bool Facet::decorateButton(WPARAM wParamLPARAM lParam) {
    // button glide calling
    if (wParam == 12321)
    {
        LPDRAWITEMSTRUCT lpDIS = (LPDRAWITEMSTRUCT)lParam;
        
        SetDCBrushColor(lpDIS->hDC, RGB(255, 192, 203));
        SelectObject(lpDIS->hDC, GetStockObject(DC_BRUSH));

        RECT rect = { 0 };
        rect.left = lpDIS->rcItem.left;
        rect.right = lpDIS->rcItem.right;
        rect.top = lpDIS->rcItem.top;
        rect.bottom = lpDIS->rcItem.bottom;

        RoundRect(lpDIS->hDC, rect.left, rect.top, rect.right, rect.bottom, 50, 50);
        // button text
        DrawText(lpDIS->hDC, TEXT("MOVE"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
        
        return TRUE;
    }
    return FALSE;
}

/*
* Call the target class' draw method
*/

void Facet::informPaint() {
    elp_region->paint();
}


/*
* Say there is more than a single push button,
* this guy picks out the correct button that got clicked
* and calls the corresponding apt function
*/

bool Facet::actionPerformed(HWND hWndWPARAM wParamLPARAM lParam)
{
    switch (LOWORD(wParam))
    {
    case 12321:
        elp_region->ellipsedSquare();
        return TRUE;
    default:
        return FALSE;
    }
}

Facet::~Facet()
{
    delete elp_region;
}

C++ Animation Code for Elliptical Region - Header File

#pragma once

#define sqLENGTH 100

class EllipticalRegion
{
public:
    EllipticalRegion(HWNDintint);
    virtual ~EllipticalRegion();
    void paint();
    void ellipsedSquare();
protected:
    HWND hWindow;
    HDC hdc;
    int window_width;
    int window_height;

    COLORREF sq_colour;
    // coordinates for the ball(circle)
    int x_square;
    int y_square;
    int previous_x;
    int previous_y;

    //ellipse coordinates
    int h; // vertice
    int k; // vertice
    const int a = 200; // major axis
    const int b = 125; // minor axis
    int x;
    int y;

    HBRUSH background_brush;
    HPEN circle_pen;
    HBRUSH sq_brush;
};


C++ Animation Code for Elliptical Region - Class File

#include "stdafx.h"
#include "EllipticalRegion.h"
#include <math.h>


EllipticalRegion::EllipticalRegion(HWND hWndint window_widthint window_height)
{
    hWindow = hWnd// save away window handle
    this->window_width = window_width// save away window width
    this->window_height = window_height// save away window width

    sq_colour = RGB(255, 255, 0); // give our square a yellow colour
    // coordinates for the ball(circle)
    x_square = 10;
    y_square = 250;
    previous_x = x_square;
    previous_y = y_square;

    //ellipse coordinates
    h = 450; // vertice
    k = 275; // vertice
    x = h - a;
    y = k - b;

    // Pen and brush matching background colour
    background_brush = CreateSolidBrush(RGB(192, 192, 192));

    // pen(purple colour) for circle
    circle_pen = CreatePen(PS_SOLID, 5, RGB(255, 0, 255));

    // brush for travelling square
    sq_brush = CreateSolidBrush(sq_colour);

    hdc = GetDC(hWindow);
}

/*
* draws the ball/circle using the apt color
*/

void EllipticalRegion::paint() {
    SelectObject(hdc, circle_pen); // use purple colour
    SelectObject(hdc, background_brush); // use background colour
    // draw an ellipse
    Ellipse(hdc, x, y, h + a, k + b);

    // erase previous square
    RECT prev_sq;
    prev_sq.left = previous_x;
    prev_sq.top = previous_y;
    prev_sq.right = previous_x + sqLENGTH;
    prev_sq.bottom = previous_y + sqLENGTH;
    FillRect(hdc, &prev_sq, background_brush);


    // draw square
    RECT sq;
    sq.left = x_square;
    sq.top = y_square;
    sq.right = x_square + sqLENGTH;
    sq.bottom = y_square + sqLENGTH;
    FillRect(hdc, &sq, sq_brush);

    previous_x = x_square;
    previous_y = y_square;
}

/*
* Repeatedly draws square so as to simulate a continuous motion
*/

void EllipticalRegion::ellipsedSquare() {
    // condition for continuing motion
    while (x_square + sqLENGTH < window_width) {
        int square_left = x_square;
        int square_right = x_square + sqLENGTH;
        int square_top = y_square;
        int square_bottom = y_square + sqLENGTH;

        // determinants for each side of the square
        int x_left_det = (int)round(((double)b / a)
            * sqrt(pow(a, 2) - pow((square_left - h), 2)));
        int x_right_det = (int)round(((double)b / a)
            * sqrt(pow(a, 2) - pow((square_right - h), 2)));
        int y_up_det = (int)round(((double)a / b)
            * sqrt(pow(b, 2) - pow((square_top - k), 2)));
        int y_down_det = (int)round(((double)a / b)
            * sqrt(pow(b, 2) - pow((square_bottom - k), 2)));

        if (square_top > k - x_left_det && square_bottom < k + x_left_det
            && square_top > k - x_right_det && square_bottom < k + x_right_det
            && square_left > h - y_up_det && square_right < h + y_up_det
            && square_left > h - y_down_det && square_right < h + y_down_det) {
            // green colour for our moving body(square) inside our ellipse
            sq_colour = RGB(0, 255, 0);
        }
        else {
            // yellow colour for our moving body(square) outside our ellipse
            sq_colour = RGB(255, 255, 0);
        }
        DeleteObject(sq_brush); // delete former brush
        sq_brush = CreateSolidBrush(sq_colour); // recreate brush with a new colour

        paint();

        x_square += 10;
        // introduce a delay between renderings
        Sleep(50);
    }
}


EllipticalRegion::~EllipticalRegion()
{
    DeleteObject(background_brush);
    DeleteObject(circle_pen);
    DeleteObject(sq_brush);
    
    ReleaseDC(hWindow, hdc);
}





<< PreviousNext >>