c++ - 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;
}
解决方案
推荐阅读
- ios - 将值从子视图页面快速传递到 Pageview 控制器
- c# - C# - Excel:删除excel中的一整行,在要删除的行的第一列具有特定值
- c# - 如何在到达控制器之前处理 C# 数据类型模型验证
- javascript - 如何从数组中的对象中为项目加上一个数字?
- reactjs - 使用 Material UI 的 Autocomplete 使用 Formik 在下拉列表中显示不同的值,但在 formik 状态下设置不同的值
- python - 带有 x 和 log(x) 的 Sympy 系列 - sympy.series.gruntz.calculate_series 的 logx 参数
- sql - 如何仅从 A 中选择与 B 中的给定 ID 匹配的行 - 表 SQL Server
- constants - CPLEX C++ 常量约束
- jquery - 只需要为 jquery.each 中的第一个元素添加活动类
- javascript - addEventListener('mousemove') 如何识别 ctx 对象?