Drawing a Crescent Moon with OpenGL - GLFW/GLEW C++
IshaqKassam
Posted on November 10, 2021
This is the 3rd article on OpenGL, drawing 2D objects in OpenGL using c++. If you haven't been following through, here is the first article where we started drawing a circle in OpenGL:
In this article, we are going to draw a Crescent Moon using the concepts of circle. We'll be using 2 Circles, with different fill colors, to give us the Crescent moon effect. Let's look at the code for circle:
void drawCircleFill(float cx, float cy, float r, int num_segments)
{
float theta = 3.1415926 * 2 / float(num_segments);
float tangetial_factor = tanf(theta);//calculate the tangential factor
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
float radial_factor = cosf(theta);//calculate the radial factor
float x = r;//we start at angle = 0
float y = 0;
glBegin(GL_POLYGON);
for (int ii = 0; ii < num_segments; ii++)
{
glVertex2f(x + cx, y + cy);//output vertex
float tx = -y;
float ty = x;
x += tx * tangetial_factor;
y += ty * tangetial_factor;
x *= radial_factor;
y *= radial_factor;
}
glEnd();
}
We'll call the method twice, to give us 2 circles, giving them different positions and color, to give us the desired crescent.
Let's call the function in the main()
as below:
glColor3f(0.8f, 0.6f, 0.2f);//golden color
drawCircleFill(500, 400, 40, 360);
glColor3f(1.0f, 1.0f, 1.0f); //white
drawCircleFill(525, 410, 40, 360);
Notice how the glColor3f
method works. If defined, the method implements the color to all the renders below the line, until reset. So the first Circle drawn takes the golden color, and the second Circle takes the color white. You can change the color of the second Circle to match the background, to attain the desired Crescent figure.
That's it for this article, see you in the upcoming!
Happy coding!
Posted on November 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.