opengl中的square填充整个显示

时间:2010-12-28 18:11:48

标签: android opengl-es

假设现在有些opengl-veterans可能会面临: - )

我正在使用open gl es在Android上开发基于tile的游戏(仅限2D)。

在介绍了opengl基础知识的几天后,我仍然不知道如何保持对象和屏幕大小之间的关系。

具体来说:我的移动显示器有480x800像素。当我指定具有以下尺寸的简单方形时,它会填满整个屏幕(?):

对象的顶点:

float vertices[] = { -1.0f, -1.0f, 0.0f, // 0, Top Left
    1.0f, -1.0f, 0.0f, // 1, Bottom Left
    1.0f, 1.0f, 0.0f, // 2, Bottom Right
    -1.0f, 1.0f, 0.0f // 3, Top Right
};

short[] indices = { 0, 1, 2, 2, 3, 0 };

onSurfaceCreated:

   public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {

gl.glMatrixMode(GL10.GL_PROJECTION);

    gl.glLoadIdentity();
    gl.glEnable(GL10.GL_BLEND);

    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
    gl.glShadeModel(GL10.GL_FLAT);
    gl.glEnable(GL10.GL_TEXTURE_2D);

    GLU.gluOrtho2D(gl, 0, Shared.dm.widthPixels, Shared.dm.heightPixels, 0);

onDrawFrame:

   @Override
    public void onDrawFrame(GL10 gl) {
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

    // Replace the current matrix with the identity matrix
    gl.glLoadIdentity();

    //Move this only
    gl.glPushMatrix();
    Log.d(Shared.LOGTAG, "X: " + offset.x + "Y: " + offset.y);
    gl.glTranslatef(offset.x, offset.y, 0);
    root.draw(gl);
    gl.glPopMatrix();
    }

任何人都可以给我一个正确方向的暗示吗?我认为它与矩阵有关?

2 个答案:

答案 0 :(得分:2)

看起来这种情况正在发生,因为您的投影矩阵正在重置。我在onSurfaceCreated中看到,您致电gluOrtho2D。这很好,但看起来你并没有转回glMatrixModel(GL_MODELVIEW)。因此,当glLoadIdentity中调用onDrawFrame时,它会重置您的投影矩阵。

当项目矩阵是标识时,坐标才会通过。 X轴上的-1和+1分别对应于窗口的左侧和右侧。在Y轴上,它们是窗口的底部和顶部。在Z轴上,它们是远近剪裁平面。

答案 1 :(得分:2)

OpenGL新手的典型误解:他们认为存在某种“一次性投影初始化”。

通常每次开始绘制时都需要重新设置整个OpenGL状态。这也会意外地覆盖投影矩阵。

<强> onSurfaceCreated:

public void onSurfaceCreated(GL10 gl, EGLConfig arg1) {
    // Just upload textures and shaders here.

<强> onDrawFrame:

@Override
public void onDrawFrame(GL10 gl) {
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

    // set everything just right before you need it
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glLoadIdentity();
    GLU.gluOrtho2D(gl, 0, Shared.dm.widthPixels, Shared.dm.heightPixels, 0);

    // order in which different matrices are set is not important,
    // but order in which each matrix is manipulated is!
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glLoadIdentity();

    // enable and configure blending on a as-needed base
    gl.glEnable(GL10.GL_BLEND);
    gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
    gl.glShadeModel(GL10.GL_FLAT);
    gl.glEnable(GL10.GL_TEXTURE_2D);

    //Move this only
    // make sure this is operating really on the modelview matrix
    // redundant in this rather simple example, but in large codebases
    // inevitable.
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    gl.glPushMatrix();
    Log.d(Shared.LOGTAG, "X: " + offset.x + "Y: " + offset.y);
    gl.glTranslatef(offset.x, offset.y, 0);
    root.draw(gl);
    gl.glPopMatrix();
}