首页 > 解决方案 > OpenGL - 用箭头键移动对象

问题描述

我想在 OpenGL 1.0 上创建一个有 9 个正方形的矩阵,首先要激活中心正方形。之后用箭头键移动它们。我用两个 for 循环创建了正方形,并添加了一个函数“activeElement”来更改活动元素的颜色。这段代码可以编译,但这不是我想要的。我不知道问题出在哪里。谢谢 :)

#include<SDL/SDL.h>
#include <iostream>
#include<GL/gl.h>
#include<GL/glu.h>
int px;
int py;


void activeElement(int px,int py, int x, int y)
{
    if( px == x && py == y){
        glColor3f(0.0,1.0,0.0);
    }else{glColor3f(1.0,0.0,0.0);}
}

void init()
{
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45,640.0/480.0,1.0,500.0);
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_DEPTH_TEST);
}





void display()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();

    glTranslatef(0.0,0.0,-20.0);


    for(int i=-1; i<=1; i++){
        for(int j=-1; j<=1 ;j++){

        glPushMatrix();
        activeElement(px, py, i,j);
        glTranslatef(4*i,4*j,0.0);
         glScalef(2.0,2.0,2.0);
        glBegin(GL_QUADS);
        glVertex3f( 0.0, 1.0, -8.0);
        glVertex3f( -1.0,1.0, -8.0);
        glVertex3f( -1.0,0.0, -8.0);
        glVertex3f( 0.0,0.0, -8.0);
        glEnd();
        glPopMatrix();

        }
    }
}


int main(int argc, char* args[])
{
    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_SetVideoMode(640,480,32,SDL_SWSURFACE|SDL_OPENGL);

    int loop=1;
    SDL_Event myevent;
    init();
    while (loop==1)
    {
        while (SDL_PollEvent(&myevent))
        {
            switch(myevent.type)
            {
                case SDL_QUIT:
                loop=0;
                break;


                if (myevent.key.keysym.sym){
                case SDLK_LEFT:
                    px =px == -1 ? 1: px-1;
                    break;
                case SDLK_RIGHT:
                    px=px ==1 ? -1 : px+1;
                    break;
                case SDLK_DOWN:
                    py = py == -1 ? 1 :py-1;
                    break;
                case SDLK_UP:
                    py = py == 1 ? -1 :py+1;
                    break;
                default:
                    break;
                }
                break;
            }
        }
        display();
        SDL_GL_SwapBuffers();
    }
    SDL_Quit();
    return 0;
}

标签: c++opengl

解决方案


推荐阅读