使用opengl java向一个方向移动一个对象

时间:2016-01-14 11:14:00

标签: java opengl

我试图在顶部顶点的方向上移动一个三角形。

取决于旋转角度。

这是我的代码:

private static void render() {
    // Clear the pixels on the screen and clear the contents of the depth buffer (3D contents of the scene)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    // Reset any translations the camera made last frame update
     glLoadIdentity();
    // Apply the camera position and orientation to the scene
    //camera.applyTranslations();
    glTranslated(0,0,-5);
    glPushMatrix();
    glRotated(f.get_direction(),0,0,1);
    glTranslated(x,y,0);
    f.draw();
    glPopMatrix();
    x+=(f.get_speed()/30)*cos(f.get_direction()+90);
    y+=(f.get_speed()/30)*sin(f.get_direction()+90);
}

关键在于无论旋转角度是什么方向, 我想根据它移动三角形。

1 个答案:

答案 0 :(得分:0)

您是否尝试根据方向向量进行翻译,但有一个简单的问题cossin参数的度数为弧度glRotate

所以我们必须创建静态函数

static double degToRad(double x)
{
    return (x / 180.0) * Math.PI;
}

而不是使用它

glLoadIdenity();

x += Math.cos(degToRad(getDirection() + 90)) * getSpeed();
y += Math.sin(degToRad(getDirection() + 90)) * getSpeed();

glTranslatef(x, y, 0);

glRotatef(getDirection(), 0, 0, 1);

drawObject();

你也可以反转运动方向,只是将当前角度从360:

glLoadIdenity();

x += Math.cos(degToRad(360 - getDirection() + 90)) * getSpeed();
y += Math.sin(degToRad(360 - getDirection() + 90)) * getSpeed();

glTranslatef(x, y, 0);

glRotatef(getDirection(), 0, 0, 1);

drawObject();