Rotating 2D Object
- by Vico Pelaez
Well I am trying to learn openGL and want to make a triangle move one unit (0.1) everytime I press one of the keyboard arrows. However i want the triangle to turn first pointing the direction where i will move one unit. So if my triangle is pointing up and I press right the it should point right first and then move one unit in the x axis. I have implemented the code to move the object one unit in any direction, however I can not get it to turn pointing to the direction it is going. The initial position of the Triangle is pointing up.
#define LENGTH 0.05
float posX = -0.5, posY = -0.5, posZ = 0;
float inX = 0.0 ,inY = 0.0 ,inZ = 0.0; // what values????
void rect(){
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glPushMatrix();
glTranslatef(posX,posY,posZ);
glRotatef(rotate, inX, inY, inZ);
glBegin(GL_TRIANGLES);
glColor3f(0.0, 0.0, 1.0);
glVertex2f(-LENGTH,-LENGTH);
glVertex2f(LENGTH-LENGTH, LENGTH);
glVertex2f(LENGTH, -LENGTH);
glEnd();
glPopMatrix();
}
void display(){
//Clear Window
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
rect();
glFlush();
}
void init(){
glClearColor(0.0, 0.0, 0.0, 0.0);
glColor3f(1.0, 1.0, 1.0);
}
float move_unit = 0.01;
bool change = false;
void keyboardown(int key, int x, int y)
{
switch (key){
case GLUT_KEY_UP:
if(rotate = 0) posY += move_unit;
else{
inX = 1.0;
rotate = 0;
}
break;
case GLUT_KEY_RIGHT:
if(rotate = -90) posX += move_unit;
else{
inX = 1.0; // is this value ok??
rotate -= 90;
}
break;
case GLUT_KEY_LEFT:
if(rotate = 90) posX -= move_unit;
else{
inX = 1.0; // is this value ok???
rotate += 90;
}
break;
case GLUT_KEY_DOWN:
if(rotate = 180) posY -= move_unit;
else{
inX = 1.0;
rotate += 180;
}
break;
case 27: // Escape button
exit(0);
break;
default:
break;
}
glutPostRedisplay();
}
int main(int argc, char** argv){
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Triangle turn");
glutSpecialFunc(keyboardown);
glutDisplayFunc(display);
init();
glutMainLoop()