c ++ opengl相机移动

时间:2018-03-15 17:55:13

标签: c++ opengl glut

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

Screenshot!

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

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

1 个答案:

答案 0 :(得分:1)

  • 您需要通过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;
}