C++ OpenGL 相机运动

c++ opengl camera movement

我无法弄清楚为什么相机不会移动!我想我设置的代码是正确的。有什么指点吗?

当我启动它时,出现了三角形,但我无法移动相机,很可能是由于缺乏经验而导致相机移动背后的我的整个方法。有人能给我指出正确的方向吗?

include "stdafx.h"
#include <GL/glut.h>
#include <GL/freeglut.h>
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

//THESE ARE MY VARIABLES
//===========
int x = 0; //|
int y = 0; //|
int z = 0; //|
//===========

//Camera Movement

void glViewport(GLint x, GLint y, GLsizei width, GLsizei height)
{
    if (WM_KEYDOWN == VK_UP) {
        std::cout << "User pressed UP!";
        ++z;
    }
    if (WM_KEYDOWN == VK_DOWN) {
        std::cout << "User pressed DOWN!";
        --z;
    }
    if (WM_KEYDOWN == VK_LEFT) {
        std::cout << "User pressed LEFT!";
        --x;
    }
    if (WM_KEYDOWN == VK_RIGHT) {
        std::cout << "User pressed RIGHT!";
        ++x;
    }
}

void display()
{
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);

    glBegin(GL_QUADS);
    glColor3f(1.0, 0, 0);
    glVertex3f(0.5, 0.5, 1);
    glColor3f(0, 1.0, 0);
    glVertex3f(0.5, 0, 1);
    glColor3f(0, 0, 1.0);
    glVertex3f(0, 0.5, 1);
    glVertex3f(0.5, 0.5, 1);

    glEnd();

    glFlush();
}

int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
    glutInitWindowSize(640, 480);
    glutInitWindowPosition(10, 10);
    glutCreateWindow("McDank");
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}
  • 您需要通过 glutKeyboardFunc()glutSpecialFunc() 向 GLUT 注册键盘回调以处理击键。
  • 你的 glViewport() 函数是......奇怪的。通过将随机 Windows 枚举与其他枚举进行比较,不确定您在此处尝试实现的目标。
  • 您实际上需要在显示函数中使用您的x/y/z变量,也许在glTranslate().

总计:

#include <GL/glut.h>

float x = 0;
float y = 0;
float z = 0;
void special( int key, int, int )
{
    const float step = 0.1;
    if( GLUT_KEY_LEFT == key )
        x -= step;
    if( GLUT_KEY_RIGHT == key )
        x += step;
    if( GLUT_KEY_UP == key )
        y += step;
    if( GLUT_KEY_DOWN == key )
        y -= step;
    glutPostRedisplay();
}

void display()
{
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho( -2, 2, -2, 2, -1, 1 );

    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();
    glTranslatef( x, y, z );

    glBegin( GL_TRIANGLES );
    glColor3ub( 255, 0, 0 );
    glVertex2f( -1, -1 );
    glColor3ub( 0, 255, 0 );
    glVertex2f(  1, -1 );
    glColor3ub( 0, 0, 255 );
    glVertex2f(  0,  1 );
    glEnd();

    glutSwapBuffers();
}

int main(int argc, char* argv[])
{
    glutInit(&argc, argv);
    glutInitWindowSize(600, 600);
    glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE );
    glutCreateWindow("McDank");
    glutSpecialFunc( special );
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}