1

I want to make the shape perform a jump while moving horizontally using the sin function but it does not even respond to the 'j' button when it is pressed ? Am still learning Opengl thouh. Any help about where is the mistake?

#include <GLUT/glut.h>
#include <math.h>

float pointone = 0;
float ydir =0;
GLboolean turn ;
void Display();
void DrawWall();
void Anim();
void Keyboard(unsigned char key, int x, int y);

int main(int argc, char** argr) {
    glutInit(&argc, argr);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(1000, 600);
    glutInitWindowPosition(50, 50);
    glutKeyboardFunc(Keyboard);
    glutIdleFunc(Anim);
    glutCreateWindow("Kbeer El Haramiya");
    glutDisplayFunc(Display);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    glPointSize(20.0);
    gluOrtho2D(0.0, 1000.0, 0.0, 600.0);
    glutMainLoop();
}

void Display() {
    glClear(GL_COLOR_BUFFER_BIT);
    DrawWall();
    glPushMatrix();
    if(pointone<=850 && turn ==true){
      pointone+=3;
      turn=true;}
    else if (pointone==0){
      turn=true;}
      else {
      turn = false;
      pointone-=3;
      }
    glTranslatef(pointone, ydir, 0);
    glBegin(GL_POLYGON);
    glColor3f(0.97f,0.96f,0.768f);
    glVertex2i(0.0f, 0.0f);
    glVertex2i(50.0f, 0.0f);
    glVertex2i(50.0f, 50.0f);
    glColor3f(0.70f,0.196f,0.12f);
    glVertex2i(0.0f, 50.0f);
    glEnd();
    glPopMatrix();
    glFlush();

}

void DrawWall(){
    glBegin(GL_POLYGON);
    glColor3f(0.97f,0.96f,0.768f);
    glVertex2i(999, 0);
    glVertex2i(999,600);
    glVertex2i(900, 600);
    glVertex2i(900, 0);
    glEnd();
    glBegin(GL_POLYGON);
    glVertex2i(0, 200);
    glVertex2i(700,200);
    glVertex2i(700, 150);
    glVertex2i(0,150);
    glEnd();
}

void Keyboard(unsigned char key, int x, int y){
    if(key == 'j')  {
      for(int i =0; i<361;i++){
        ydir =sin(i);
        glutPostRedisplay();
    }

}

}
void Anim(){
    glutPostRedisplay();
}
Hebazzz
  • 15
  • 3

2 Answers2

0

You have to update ydir somewhere in the Display() function. When you try to update it outside of this in a loop, there is only one single redraw scheduled after the Keyboard function has ended.

The code could look (for example) somehow like this:

int yint = -1; //-1 means no moving

void Display() {
    if (yint > 360) // Reset when > 360°
        yint = -1; 
    if (yint >= 0 && yint <= 360) //Update until 360° is reached
        yint++;

    float ydir = sin(yint);

    //Draw code here
}

void Keyboard(unsigned char key, int x, int y){
    if(key == 'j')
        yint = 0;
}
BDL
  • 21,052
  • 22
  • 49
  • 55
0

The solution was simple, I was supposed to Create the window before calling Keyboardfunc ! :)

Hebazzz
  • 15
  • 3