I need to draw a sun that keep rotating (spinning) on it original position / pivot point that placed on position (450, 450), but it now is not spinning on it original point instead it continuing spinning 360 degree over the screen and back to original position again and again. Anyone know how to solve it and keep the sun spinning at it original position, please modify the code. Appreciate those help.
Code for Sun
#include <windows.h> // for MS Windows
#include <GL/glut.h> // GLUT, include glu.h and gl.h
#include <math.h>
float sunAngle = 0.0f; // Angle for sun rotation
// Drawing Circle
void circle(GLfloat rx, GLfloat ry, GLfloat cx, GLfloat cy)
{
glBegin(GL_POLYGON);
glVertex2f(cx, cy);
for (int i = 0; i <= 360; i++)
{
float angle = i * 3.1416 / 180;
float x = rx * cos(angle);
float y = ry * sin(angle);
glVertex2f((x + cx), (y + cy));
}
glEnd();
}
// Drawing Sun
void sun()
{
glPushMatrix();
glRotatef(sunAngle, 0.0, 0.0, 1.0);
// Draw the object
glColor3f(1.0f, 1.0f, 0.0f); // Yellow color
circle(20, 30, 450, 450);
glTranslatef(-450, -450, 0.0);
glPopMatrix();
}
void update(int value) {
// Update sun angle for rotation
sunAngle += 1.0f;
if (sunAngle > 360) {
sunAngle -= 360;
}
// tell GLUT to call update again in 20 milliseconds
glutTimerFunc(20, update, 0);
}
void display (void){
glClear(GL_COLOR_BUFFER_BIT);
//Sky Color
glColor3ub(30, 144, 255);
glBegin(GL_POLYGON);
glVertex2d(0, 0);
glVertex2d(500, 0);
glVertex2d(500, 500);
glVertex2d(0, 500);
glEnd();
sun();
glFlush();
glutSwapBuffers();
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(900, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("Sun");
init();
glutDisplayFunc(display);
glutTimerFunc(16, update, 0);
glutMainLoop();
return 0;
}
(Now I don't have environment to try OpenGL, but, I think...)
Center of rotation (of
glRotatef) is origin.So, May be,
That is, put the circle at origin, and rotate it around origin, then translate it to (450,450).
Then...
I tried my this answer.
(Since I don't have
GLUT, I usedGLFW(andGLEW), but this point will not be problem.)As a result, yellow ellipse is rotating at same position. So, I think this answer is not wrong.
My Test Code:
Code edited to to handle aspect ratio:
NeedToUpdateScaleis on.NeedToUpdateScaleis set to on when window resized (using callback. For GLUT,glutReshapeFunc()can be used.)Here, I used
glScaledto adujst aspect ratio, but usually,glOrtho()etc will be used.Now I created GLUT version code.
(In this version, the axis drawing code I added into above code is omitted because we can grasp about scaling result with existing sky-colored box)
Changed points are commented in code below.
Running this code, sky colored square region appears in the upper right area of the window, and a yellow ellipse rotates near the upper right corner of the region.