在 OPENGL 上按下某个键时,我的形状不想移动

My Shape does not want to move when press a key on OPENGL

我想使用 sin 函数让形状在水平移动时执行跳跃,但按下 'j' 按钮时它甚至没有响应? 不过我还在学习 Opengl。大家帮忙看看哪里错了?

#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();
}

您必须在 Display() 函数的某处更新 ydir。当您尝试在此循环之外更新它时,在 Keyboard 函数结束后只安排了一次重绘。

代码可能看起来(例如)像这样:

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;
}

解决方案很简单,我应该在调用 Keyboardfunc 之前创建 window! :)