shooting bullets opengl - opengl

I have the following code which draws me a "spacecraft" which I'm able to ctrol with my arrow keys to spin clockwise and anti-clockwise. I'm trying to get the spacecraft shoot bullets when another key is pressed (it can be any key). I am so new to OpenGL that I'm confused on how to do it. I have tried so many methods but none of them work. Below is the code where I draw my spaceship and how I control it. Can someone help me with the bullets please?
struct
{
float rotateSpaceCraft;
} scene;
void SpaceCraft (){
glBegin(GL_TRIANGLE_FAN);
//specify the vertices to draw Ship in 2d space
glColor3f(1.0, 0.0, 1.0);
glVertex2f( X_CENTRE + LENGTH * 0, Y_CENTRE + LENGTH * 12);
glColor3f(1.0, 1.0, 0.0);
glVertex2f( X_CENTRE - LENGTH * 8, Y_CENTRE - LENGTH * 8);
glColor3f(0.0, 1.0, 1.0);
glVertex2f( X_CENTRE - LENGTH * 0, Y_CENTRE - LENGTH * 0);
glColor3f(1.0, 0.0, 0.0);
glVertex2f( X_CENTRE + LENGTH * 8, Y_CENTRE - LENGTH * 8);
glEnd();
}
void display(void)
{
glClear (GL_COLOR_BUFFER_BIT); /* clear window */
glColor3f(1.0, 1.0, 1.0); /* white drawing objects */
/* define object to be drawn as a square polygon */
glPushMatrix();
glRotatef(scene.rotateSpaceCraft, 0.0, 0.0, 1.0);
SpaceCraft();
glPopMatrix();
glutSwapBuffers();
glFlush(); /* execute drawing commands in buffer */
}
static void specialKey(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_LEFT:
scene.rotateSpaceCraft = fmod(scene.rotateSpaceCraft + 7, 360);
break;
case GLUT_KEY_RIGHT:
scene.rotateSpaceCraft = fmod(scene.rotateSpaceCraft - 7, 360);
break;
default:
break;
}
glutPostRedisplay();
}
int main(int argc, char** argv)
{
/* window management code ... */
/* initialises GLUT and processes any command line arguments */
glutInit(&argc, argv);
/* use single-buffered window and RGBA colour model */
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
/* window width = 400 pixels, height = 400 pixels */
glutInitWindowSize (600, 600);
/* window upper left corner at (100, 100) */
glutInitWindowPosition (250, 50);
/* creates an OpenGL window with command argument in its title bar */
glutCreateWindow ("Asteroids");
glutKeyboardFunc(key);
glutSpecialFunc(specialKey);
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}

Step by Step you could do it this way:
Create a spaceship object which holds rotation of the spaceship
Create a bullet object ( struct or class ), which holds the vector of the bullet, the start position ( and the time at which the bullet has been fired, you will need it later )
Create a scene object which holds a list of all bullets fired and the spaceship
Catch Key Events from Windows or any other platform you are using
When the bullet is fired, use the rotation and position of your spaceship to determine the position of the new bullet and the vector of it.
Some pseudo code for the structure:
struct Bullet {
Vector3 Position;
Vector3 Rotation;
}
struct {
struct {
Vector3 Position;
Vector3 Rotation;
} Ship;
Vector<Bullet*> Bullets;
} Scene;
....:
void Update(void) {
if (Key.IsPressed(Space)) {
CreateNewBullet();
}
}
void UpdateBullets(void) {
for (Bullet bullet in Scene.Bullets)
{
// Delete bullets here if not longer used
// and move all others
}
}
void Draw(void) {
// Draw spaceship here
....
// Draw bullets
for (Bullet bullet in Scene.Bullets) {
DrawBullet(bullet);
}
}

I also recommend using VBO but if you want to do it with the deprecated set then what you are looking for is to render a bullet similar to your SpaceCraft() function. A bullet will need to travel so you will need to translate its position every frame.
glTranslatef(x, 0.0f, 0.0f);
This will translate the bullet x amount in the x axis. Therefore you will need a variable that increments certain amount per frame and passes it to your new Bullet() function. You can store the translation X amount just like you did with struct
{
float rotateSpaceCraft;
} scene;

Related

grid not showing (it is all black)

I didn't want to go back to the same question from yesterday, however before I am able to use the function to turn on and off the grid, I first need to know if my grid is actually working, I have been making new projects all night trying to display the grid but it isn't showing, the screen is always black and nothing is there at all.
#include "include\freeglut.h" // OpenGL toolkit - in the local shared folder
#include <iostream>
//set up some constants
#define X_CENTRE 0.0 /* centre point of square */
#define Y_CENTRE 0.0
#define LENGTH 1.0 /* lengths of sides of square */
GLfloat red = 1.0, green = 1.0, blue = 1.0;
int w;
int h;
/* reshape callback function
executed when window is moved or resized */
void reshape(int width, int height)
{
glViewport(0, 0, width, height);
/* uses orthographic (parallel) projection
use xmin = -1, xmax = 1
ymin = -1, ymax = 1
znear = -1, zfar = 1 - not relevant here (2D) */
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
}
/* display callback function
called whenever contents of window need to be re-displayed */
//this is the all important drawing method - all drawing code goes in here
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT); /* clear window */
//glColor3f(red, green, blue); /* white drawing objects */
glColor3f(0.8, 0.8, 0.8);
GLint i;
glEnable(GL_LINE_STIPPLE); //Activates the line-style feature
glLineStipple(1, 0xAAAA); // Plots a dashed polyline
glBegin(GL_LINES);
for (i = 2; i <= 9; i++)
{
glVertex3f(i * 0.1 * w, 0.0, 0.0);
glVertex3f(i * 0.1 * w, 0.9 * h, 0.0);
}
for (i = 1; i <= 9; i++)
{
glVertex3f(0.1 * w, i * 0.1 * h, 0.0);
glVertex3f(w, i * 0.1 * h, 0.0);
}
glEnd();
glDisable(GL_LINE_STIPPLE);
glFlush(); /* execute drawing commands in buffer */
}
/* graphics initialisation */
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0); /* window will be cleared to black */
}
//rename this to main(...) and change example 2 to run this main function
int main(int argc, char** argv)
{
/* window management code ... */
/* initialises GLUT and processes any command line arguments */
glutInit(&argc, argv);
/* use single-buffered window and RGBA colour model */
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
/* window width = 400 pixels, height = 400 pixels */
glutInitWindowSize(400, 400);
/* window upper left corner at (100, 100) */
glutInitWindowPosition(100, 100);
/* creates an OpenGL window with command argument in its title bar */
glutCreateWindow("Example 1");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
The variables w and h a re not initialized. Initialize the variables by 1:
int w = 1;
int h = 1;
However, if you want to set the vertex coordinates in window space, you have to change the orthographic projection. The projection matrix defines the area (volume) with respect to the observer (viewer) which is projected onto the viewport. At orthographic projection, this area (volume) is defined by 6 distances (left, right, bottom, top, near and far) to the viewer's position.
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);
glOrtho(0.0, (float)w, (float)h, 0.0, -1.0, 1.0);
Function reshape:
void reshape(int width, int height)
{
glViewport(0, 0, width, height);
/* uses orthographic (parallel) projection
use xmin = -1, xmax = 1
ymin = -1, ymax = 1
znear = -1, zfar = 1 - not relevant here (2D) */ #
w = width;
h = height;
glMatrixMode(GL_PROJECTION);
glOrtho(0.0, (float)w, (float)h, 0.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}

How to capture keyboard input to stop an animation in opengl code.

I have some code to move a toy car from left to right.
I want to transform the code to stop its movement by the pressing of any key for example 's'....could someone help me do that...here is my code so far.
#include <GL/glut.h> // Header File For The GLUT Library
#include <GL/gl.h> // Header File For The OpenGL32 Library
#include <GL/glu.h> // Header File For The GLu32 Library
//#include <unistd.h> // Header File For sleeping.
/* ASCII code for the escape key. */
#define ESCAPE 27
/* The number of our GLUT window */
int window;
/* rotation angle for the triangle. */
float rtri = 0.0f;
/* rotation angle for the quadrilateral. */
float rquad = 0.0f;
/* A general OpenGL initialization function. Sets all of the initial parameters. */
// We call this right after our OpenGL window is created.
void InitGL(int Width, int Height)
{
// This Will Clear The Background Color To Black
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0); // Enables Clearing Of The Depth Buffer
glDepthFunc(GL_LESS); // The Type Of Depth Test To Do
glEnable(GL_DEPTH_TEST); // Enables Depth Testing
glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // Reset The Projection Matrix
gluPerspective(45.0f,(GLfloat)Width/(GLfloat)Height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
}
/* The function called when our window is resized (which shouldn't happen, because we're fullscreen) */
void ReSizeGLScene(int Width, int Height)
{
if (Height==0) // Prevent A Divide By Zero If The Window Is Too Small
Height=1;
glViewport(0, 0, Width, Height); // Reset The Current Viewport And Perspective Transformation
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f,(GLfloat)Width/(GLfloat)Height,0.1f,100.0f);
glMatrixMode(GL_MODELVIEW);
}
float ballX = -0.5f;
float ballY = 0.0f;
float ballZ = 0.0f;
void drawBall(void) {
glColor3f(0.0, 1.0, 0.0); //set ball colour
glTranslatef(ballX,ballY,ballZ); //moving it toward the screen a bit on creation
//glRotatef(ballX,ballX,ballY,ballZ);
glutSolidSphere (0.3, 20, 20); //create ball.
glTranslatef(ballX+1.5,ballY,ballZ); //moving it toward the screen a bit on creation
glutSolidSphere (0.3, 20, 20); //
}
/* The main drawing function. */
void DrawGLScene()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear The Screen And The Depth Buffer
glLoadIdentity(); // Reset The View
glTranslatef(rtri,0.0f,-6.0f); // Move Left 1.5 Units And Into The Screen 6.0
//glRotatef(rtri,1.0f,0.0f,0.0f); // Rotate The Triangle On The Y axis
// draw a triangle (in smooth coloring mode)
glBegin(GL_POLYGON); // start drawing a polygon
glColor3f(1.0f,0.0f,0.0f); // Set The Color To Red
glVertex3f(-1.0f, 1.0f, 0.0f); // Top left
glVertex3f(0.4f, 1.0f, 0.0f);
glVertex3f(1.0f, 0.4f, 0.0f);
glColor3f(0.0f,1.0f,0.0f); // Set The Color To Green
glVertex3f( 1.0f,0.0f, 0.0f); // Bottom Right
glColor3f(0.0f,0.0f,1.0f); // Set The Color To Blue
glVertex3f(-1.0f,0.0f, 0.0f);// Bottom Left
//glVertex3f();
glEnd(); // we're done with the polygon (smooth color interpolation)
drawBall();
rtri+=0.005f; // Increase The Rotation Variable For The Triangle
if(rtri>2)
rtri=-2.0f;
rquad-=15.0f; // Decrease The Rotation Variable For The Quad
// swap the buffers to display, since double buffering is used.
glutSwapBuffers();
}
/* The function called whenever a key is pressed. */
void keyPressed(unsigned char key, int x, int y)
{
/* sleep to avoid thrashing this procedure */
// usleep(100);
/* If escape is pressed, kill everything. */
if (key == ESCAPE)
{
/* shut down our window */
glutDestroyWindow(window);
/* exit the program...normal termination. */
exit(0);
}
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);
/* get a 640 x 480 window */
glutInitWindowSize(640, 480);
/* the window starts at the upper left corner of the screen */
glutInitWindowPosition(0, 0);
/* Open a window */
window = glutCreateWindow("Moving Car");
/* Register the function to do all our OpenGL drawing. */
glutDisplayFunc(&DrawGLScene);
/* Go fullscreen. This is as soon as possible. */
//glutFullScreen();
/* Even if there are no events, redraw our gl scene. */
glutIdleFunc(&DrawGLScene);
/* Register the function called when our window is resized. */
glutReshapeFunc(&ReSizeGLScene);
/* Register the function called when the keyboard is pressed. */
glutKeyboardFunc(&keyPressed);
/* Initialize our window. */
InitGL(640, 480);
/* Start Event Processing Engine */
glutMainLoop();
return 1;
}
conditionally disable the following bit of code:
rtri+=0.005f; // Increase The Rotation Variable For The Triangle
if(rtri>2)
rtri=-2.0f;
rquad-=15.0f; // Decrease The Rotation Variable For The Quad
this can be done by adding the following to the keyPressed function
if (key == S)
{
updateGeom = false;//stop updating
}
if (key == D)
{
updateGeom = true;//start updating
}
and changing the above mentioned code as
if(updageGeom){
rtri+=0.005f; // Increase The Rotation Variable For The Triangle
if(rtri>2)
rtri=-2.0f;
rquad-=15.0f; // Decrease The Rotation Variable For The Quad
}
you need to add a global boolean updateGeom as well

How to let a wheel to rotate around its center in (GLUT) openGL without pressing any key or clicking the mouse button

I need to make this wheel to make a rotation animation around its center in openGL continuously without clicking the mouse,because the wheel makes its rotation if the left button of the mouse is clicked!!, this is the wheel:
This is the code I used to draw the wheel and to make the rotation:
#include <freeglut.h>
#include <glaux.h>
void whiteStud()
{
glColor3f(1.0, 1.0, 1.0);
glutSolidSphere(0.01, 16, 16);
}
void blackWheel()
{
glColor3f(0.129412, 0.129412, 0.129412);
glutSolidSphere(0.1, 16, 16);
}
void wheelWithStuds()
{
/**********************************/
int iTimeElapsed = glutGet(GLUT_ELAPSED_TIME);
float fScale= 0.5f;
long i;
/**********************************/
/* clear all pixels */
glClear(GL_COLOR_BUFFER_BIT);
/**********************************/
glPushMatrix();
glTranslatef(0.25, 0.25, 0.0);
glRotatef(iTimeElapsed * fScale,0.0,0.0,1.0);
blackWheel(); // draw the wheel without studs.
/**********************************/
// five studs, step 72 degree (72*5=360 degree).
for (i=0; i<5; i++) {
glPushMatrix();
glRotatef(72*i,0.0,0.0,1.0); // rotate coordinate 72 degree.
glTranslatef(0.04, 0.0, 0.0);// translate on the rotated coordinate.
whiteStud(); // draw the stud.
glPopMatrix();
}
glTranslatef(0.0, 0.0, 0.0);// translate in order to draw a stud at the center of the wheel.
whiteStud();// draw the stud at the center of the wheel.
/**********************************/
/* don't wait! start processing buffered OpenGL routines */
glFlush();
glPopMatrix();
/**********************************/
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(400, 400);
glutInitWindowPosition(10, 10);
glutCreateWindow("(-Rotating Car Wheel-)");
/* select clearing (background) color */
glClearColor(1.0, 1.0,1.0, 1.0);
/* initialize viewing values */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glutDisplayFunc(wheelWithStuds);
glutMainLoop();
return 0;
}
I want this wheel to rotate by itself without clicking the left button of the mouse, how can I perform this?
Here is a new draw_wheel() with the desired motion. Notably, you forgot glutPostRedisplay() at the end of the draw method; this function tells glut to redraw the window. Also you were not resetting your first call to glTranslatef(), so every time you clicked the window the object got further away from its original position.
void draw_wheel()
{
int iTimeElapsed = glutGet(GLUT_ELAPSED_TIME);
float fRevolveScale1 = 0.2f;
float fRevolveScale2 = 0.4f;
long i;
// clear all pixels
glClear(GL_COLOR_BUFFER_BIT);
// push temp state
glPushMatrix();
// translate to center
glTranslatef(0.5f, 0.5f, 0.0);
// rotate around pivot
glRotatef(iTimeElapsed * fRevolveScale1,0.0,0.0,1.0);
// translate to planet location
glTranslatef(0.25f, 0.25f, 0.0);
glRotatef(iTimeElapsed * fRevolveScale2,0.0,0.0,1.0);
glColor3f(0.129412f, 0.129412f, 0.129412f);
glutSolidSphere(0.1f, 16, 16);
// five bolts, step 72 degree (72*5=360 degree)
glColor3f(1.0, 1.0, 1.0);
for(i=0; i<5; ++i)
{
glPushMatrix();
glRotatef(72.0f*i,0.0,0.0,1.0); // rotate coordinate 72 degree
glTranslatef(0.04f, 0.0, 0.0);// translate on the rotated coordinate
glutSolidSphere(0.01f, 16, 16);
glPopMatrix();
}
glTranslatef(0.0f, 0.0f, 0.0f);// translate on the rotated coordinate
glutSolidSphere(0.01, 16, 16);
// pop temp state
glPopMatrix();
glFlush();
glutPostRedisplay();
}

How to make a draggable object with OpenGL?

I have a code with which I generate a pawn in OpenGL. However, I want to make its parts draggable. My question is more of a general one, but here's the code for my pawn so that you get an idea of what I'm doing:
int main()
{
/* open gl initialization */
while(running())
{
glClear(GL_COLOR_BUFFER_BIT + GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glColor3ub(0, 0, 0);
/* the basis of the pawn */
glPushMatrix();
glScalef(1.6, 1.6, 0.8);
glTranslatef(0.0, 0.0, -2.7 - offset);
drawSmoothUnityEllipsoidPatch(0, 2*M_PI, 0, M_PI /2 );
glPopMatrix();
/* upped ellipsoid */
glPushMatrix();
glScalef(0.8, 0.8, 0.15);
glTranslatef(0.0 - offset, 0.0, 6.0);
drawSmoothUnitySphere();
glPopMatrix();
/* lower ellipsoid */
glPushMatrix();
glScalef(1.2, 1.2, 0.15);
glTranslatef(0.0 - offset, 0.0, -10.0);
drawSmoothUnitySphere();
glPopMatrix();
/* the cone */
glPushMatrix();
glScalef(1.0, 1.0, 3.5);
glTranslatef(0.0 + offset, 0.0, -0.5);
drawSmoothUnityCone();
glPopMatrix();
/* the sphere on top of the pawn */
glPushMatrix();
glScalef(0.7, 0.7, 0.7);
glTranslatef(0.0, 0.0, 2.3 + offset);
drawSmoothUnitySphere();
glPopMatrix();
glfwTerminate();
return 0;
}
where offset is irrelevant. The functions drawSmoothUnity(shape) just draw a unity shape in the centre of the coordinate system. I want to te able to drag and drop any of these shapes in the visible area (800x600, my window-size).
You can use gluUnproject to map your cursor position from screen space into world space. By tracking the delta of the 3D world coordinates when the mouse button was first clicked to the current position (after dragging) this gives you the x,y&z values you should use to translate your object.
Also, it should be 'glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);'
This is kind of off the top of my head and is psuedocodish. This doesn't take into account any selection or any of that. So, clicking down and moving the mouse would move the object even if the object wasn't under the mouse cursor when you clicked. You'll obviously need to add mouse handlers.
glm::dvec3 original_position;//position of object when we start moving
glm::dvec3 world_anchor;//world space coordinates of where we left clicked
glm::ivec2 screen_anchor;//screen space coordinates of where we left clicked
Object object;
OnLButtonDown(int x, int y)//x,y = where we clicked
{
original_position = object.GetPosition();
screen_anchor = ivec2(x,y);//screen coords where we clicked
gluUnproject(x,y,0,modelview_matrix,projection_matrix,viewport,&world_anchor.x,
&world_anchor.y,&world_anchor.z);
}
OnMouseMove(int x, int y) //x,y = current mouse cursor position
{
if(left_button_down)
MoveObject(screen_anchor.x-x,screen_anchor.y-y);
}
}
MoveObject(int dx, int dy)//dx,dy = distance from current mouse position to screen_anchor
{
glm::dvec3 world_position;//current mouse position in world coordinates
gluUnProject(dx,dy,0,modelview_matrix,projection_matrix,viewport,&world_position.x,
&world_position.y,&world_position.z);
glm::dev3 world_delta = world_anchor-world_position;
object.SetPosition(original_position+world_delta);
}

OpenGL, Rotation around a point doesn't work still around the origin

I did the (translate, rotate, translate) thing but it still rotates around the origin. All I did is when you press the r key, the trick will begin which is (translate, rotate, translate). the result is that it is still rotating around the origin
#include <gl/glut.h>
void OnKeyPress(unsigned char key, int x, int y)
{
if (key == 27)
exit(0);
switch(key)
{
case 'r':
case 'R':
// trick start here *********************
glTranslatef(-60,-20,0);
glRotatef(10, 0, 0, 1);
glTranslatef(60, 20, 0);
glutPostRedisplay();
break;
};
}
void OnDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f,0.5f,1.0f);
glBegin(GL_TRIANGLES);
glVertex2f(20, 20);
glVertex2f(60, 20);
glVertex2f(20, 100);
glEnd();
glFlush();
}
int main( int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Lab1" );
glutDisplayFunc(OnDisplay);
glutKeyboardFunc(OnKeyPress);
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-100, 100, -100, 100);
glutMainLoop();
return 0;
}
You need to switch the order of your glTranslate calls because the last transformation done is the first one applied to the vertex. See, every transformation is a matrix, whose your current matrix is multiplied to. The resulting matrix is then multiplied to the vertex in order to determine its final position.
So if you have:
glTranslatef(-60,-20,0); (T1)
glRotatef(10, 0, 0, 1); (R)
glTranslatef(60, 20, 0); (T2)
and also have an old matrix Mo stored from the previous frame, you will have:
M = (((Mo * T1) * R) * T2)
in the end, this M is multiplied by each vertex Vo, to determine its final position:
V = M * Vo
Matrix multiplications are non-commutative, but they are associative, thus the parenthesis order does not matter, and all these transformations are mathematically equivalent to:
V = Mo * T1 * R * (T2 * Vo)
Note that (T2 * Vo) is a vertex transformed by T2 (your last translation). If we call it V1, we have:
V = Mo * T1 * (R * V1)
See that V1, your original vertex transformed by T2, is now in turn being transformed by the rotation R in (R * V1), resulting in another vertex, now translated and then rotated. Keep going on solving the expression right to left and you will have all the transformations applied to the vertex in the inverse order on where they were "called" in the OpenGL code.
I assume you know why you have to translate-rotate-untranslate in order to have the rotation around the point you want, but you got it wrong when you said that the "thing" was being rotated around the origin in your code. In fact, if you pay attention, you will notice it was being rotated around point (-60, -20).
Finally, you are not using the model-view matrix, but doing all the transformation using the perspective matrix (which incidentally works, since you are not resetting it every frame, as most applications do). You should not be doing this, but instead, using the GL_MODELVIEW to these kind of transformation. Try finishing your Initializing function with:
...
Set_Transformations();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glutMainLoop();
}
Flip it around (+, rot, -) instead of (-, rot, +):
#include <gl/glut.h>
int angle = 0;
void OnKeyPress(unsigned char key, int x, int y)
{
if (key == 27)
exit(0);
switch(key)
{
case 'r':
case 'R':
angle += 10;
glutPostRedisplay();
break;
};
}
void OnDisplay()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f,0.5f,1.0f);
glClearColor(1.0, 1.0, 1.0, 0.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(-100, 100, -100, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// trick start here *********************
glTranslatef(60, 20, 0);
glRotatef( angle, 0, 0, 1);
glTranslatef(-60,-20,0);
glBegin(GL_TRIANGLES);
glColor3ub(0,0,255);
glVertex2f(20, 20);
glColor3ub(255,0,0);
glVertex2f(60, 20);
glColor3ub(0,0,255);
glVertex2f(20, 100);
glEnd();
glFlush();
}
int main( int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA);
glutInitWindowPosition(100, 100);
glutInitWindowSize(800, 600);
glutCreateWindow("OpenGL Lab1" );
glutDisplayFunc(OnDisplay);
glutKeyboardFunc(OnKeyPress);
glutMainLoop();
return 0;
}