如何在OpenGL中使用键盘从另一个类移动一个对象?

时间:2015-05-29 19:38:46

标签: c++ opengl glut opengl-1.x

如果我的Sphere是一个类,如何从OpenGL键盘移动我的Sphere?

主:

#include "glos.h"
#include <gl.h>
#include <glu.h>
#include <glut.h>
#include <glaux.h>
#include <math.h>  
#include"Sphere.cpp"
using namespace std;

void myinit(void);
void CALLBACK myReshape(GLsizei w, GLsizei h);
void CALLBACK display(void);

Sphere sfera1(0, 0, 0, 1);
Sphere sfera2(5, 0, 0, 1);


void myinit(void)
{
    glEnable(GL_LIGHTING); // activare iluminare
    glEnable(GL_LIGHT0);    // activare sursa 0

    glDepthFunc(GL_LESS);
    glEnable(GL_DEPTH_TEST);
}

void CALLBACK display(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    sfera1.draw();
    sfera2.draw();
    glFlush();
}

void CALLBACK myReshape(GLsizei w, GLsizei h)
{
    if (!h) return;
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(65.0, (GLfloat)w / (GLfloat)h, 1.0, 20.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glRotated(25, 0.0, 1.0, 1.0);
    glTranslatef(0.0, -1.0, -6.0);
}

int main(int argc, char** argv)
{
    auxInitDisplayMode(AUX_SINGLE | AUX_RGB | AUX_DEPTH16);
    auxInitPosition(0, 0, 850, 850);
    auxInitWindow("Iluminarea");
    myinit();
    glutSpecialFunc(sfera1.keyboardown);
    auxReshapeFunc(myReshape);
    auxMainLoop(display);
    return(0);
}

球类:

#include "glos.h"
#include <glut.h>
#include <math.h>  
class Sphere{

public:
    float x, y, z, r;
    bool testColision = false;
    Sphere(float x, float y, float z, float r){
        this->x = x;
        this->y = y;
        this->z = z;
        this->r = r;
    }
    bool colision(Sphere sfera){
        float d = sqrt(pow(++x - ++sfera.x, 2) + pow(++y - ++sfera.y, 2) + pow(++z - ++sfera.z, 2));
        if (d <= r + sfera.r){
            return true;
        }
        else{
            return false;
        }
    }
    void draw(){
        glPushMatrix();
        glTranslatef(x, y, z);
        glutSolidSphere(r, 100, 100);
        glPopMatrix();
    }
    void keyboardown(int key, int x, int y) {
        if (key == 'w')
            this->x += x;
        if (key == 'a')
            this->x -= x;
        if (key == 'd')
            this->y += y;
        if (key == 's')
            this->y -= y;

        glutPostRedisplay();
    }
};

我尝试用glutSpecialFunc(sfera1.keyboardown)或auxKeyFunc(AUX_RIGHT,sphere1.MutaDreapta1)移动它,但在这两种情况下我都不能......有人能告诉我该怎么做吗?

1 个答案:

答案 0 :(得分:-1)

过剩和真的应该是互操作的吗? 或者是glutSpecialFunc for auxSpecialFunc的拼写错误? ; - )

无论如何,使用(过剩)KeyboardFunc通常会更好(在某些系统上,Up / Down / Special正在做奇怪的事情)。