LWJGL在给定平面上获取鼠标坐标

时间:2014-03-20 03:56:44

标签: java opengl lwjgl

到目前为止,我已经获得了获取鼠标在世界中的位置的代码,但是我需要在给定的平面(z=0)上获取它,我该怎么做呢?这是我的选择代码:

static public Vector3f getMousePositionIn3dCoords(int mouseX, int mouseY) {

    viewport.clear();
    modelview.clear();
    projection.clear();
    winZ.clear();;
    position.clear();
    float winX, winY;

    GL11.glGetFloat( GL11.GL_MODELVIEW_MATRIX, modelview );
    GL11.glGetFloat( GL11.GL_PROJECTION_MATRIX, projection );
    GL11.glGetInteger( GL11.GL_VIEWPORT, viewport );

    winX = (float)mouseX;
    winY = (float)mouseY;

    GL11.glReadPixels(mouseX, mouseY, 1, 1, GL11.GL_DEPTH_COMPONENT, GL11.GL_FLOAT, winZ);

    float zz = winZ.get();
    GLU.gluUnProject(winX, winY, zz, modelview, projection, viewport, position);
    Vector3f v = new Vector3f(position.get(0),position.get(1),position.get(2));
    return v ;
}

1 个答案:

答案 0 :(得分:0)

我已经解决了,对于任何感兴趣的人,这是我修改的代码,用于在z = 0时获取世界中的x和y:

static public Vector3f getMouseOnPlaneZ(int mouseX, int mouseY)
{

    viewport.clear();
    modelview.clear();
    projection.clear();
    winZ.clear();;
    position.clear();
    float winX, winY;

    GL11.glGetFloat( GL11.GL_MODELVIEW_MATRIX, modelview );
    GL11.glGetFloat( GL11.GL_PROJECTION_MATRIX, projection );
    GL11.glGetInteger( GL11.GL_VIEWPORT, viewport );

    winX = (float)mouseX;
    winY = (float)mouseY;

    GLU.gluUnProject(winX, winY, 0.0f, modelview, projection, viewport, position);
    GLU.gluUnProject(winX, winY, 1.0f, modelview, projection, viewport, position1);

    float zeropoint, zeroperc;
    double posXt, posYt, posZt;
    posXt = position.get(0) - position1.get(0);
    posYt = position.get(1) - position1.get(1);
    posZt = position.get(2) - position1.get(2);

    if ((position.get(2) < 0.0 && position1.get(2) < 0.0) || (position.get(2) > 0.0 && position1.get(2) > 0.0))
        return null;

    zeropoint = 0.0f - (float)position.get(2);

    //Find the percentage that this point is between them
    zeroperc = (zeropoint / (float)posZt);

    Vector3f v = new Vector3f((float)position.get(0) + (float)(posXt * zeroperc),(float)position.get(1) + (float)(posYt * zeroperc),(float)position.get(2) + (float)(posZt * zeroperc));
    return v ;

}