3

我正在尝试使用 opengles,并制作了一些在屏幕上移动的简单方块:

    //inside my renderScreen() method, called from onDrawFrame()
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    if (gameObjects != null) {
        // iterate and draw objects
        for (GameObject obj : gameObjects) {
            if (obj != null) {
                gl.glLoadIdentity();
                gl.glTranslatef(obj.posX, obj.posY, 0.0f);
                obj.doDraw(gl);
            }

很简单,将对象绘制到屏幕上(仍在工作)。现在我想通过基于触摸输入转换投影矩阵来在屏幕上拖动。我在之前的代码上方添加了这段代码(在绘制对象之前)

//change projection matrix
    gl.glMatrixMode(GL10.GL_PROJECTION);
    gl.glLoadIdentity();
    gl.glTranslatef(-cameraX, -cameraY, 0.0f); //cameraX and cameraY set in updateGame()  

updateGame 只是从 MyPanel.getDiffX() 获取那些,其中 DiffX 就是您的手指移动了多少:

// Inside MyPanel Class
public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                startingX = event.getX();
                startingY = event.getY();
                MyRenderer.addObject(new GameSquare(event.getX(), v
                        .getHeight() - event.getY())); // Y is inverted!
            }
            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                diffX = (event.getX() - startingX) / 100;
                //diffY = (event.getX() - startingY) / 1000;
                Log.d("diffX" ,Float.toString(diffX));
            }
            return true;
        }

现在,如果我使用代码来转换投影矩阵,我再也看不到屏幕上的任何对象(只是 glClear 颜色)。有谁知道发生了什么?我使用的矩阵错了吗?

4

2 回答 2

1

当您将 cameraX 和 cameraY 设置为 0 时会发生什么?通过改变投影矩阵,你确定你没有覆盖一些以前设置的值吗?

除此之外,您应该通过 -cameraX 和 -cameraY 进行翻译。想一想,如果你想让你的相机在 (10, 10) 的位置,那么 (10, 10) 的任何东西在被相机转换后都应该在原点,逻辑翻译是 (-10, -10) . 你不是在翻译世界上的相机,而是在翻译相机周围的世界。

编辑:让我建议一种替代方法,它不会改变投影矩阵。

//inside my renderScreen() method, called from onDrawFrame()
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glTranslate(-cameraX, -cameraY, 0); //Apply the camera here
if (gameObjects != null){
    // iterate and draw objects
    for (GameObject obj : gameObjects) {
        if (obj != null) {
            gl.glPushMatrix(); //Note this line here, we 'push' a matrix onto the top
            gl.glTranslatef(obj.posX, obj.posY, 0.0f);
            obj.doDraw(gl);
            gl.glPopMatrix(); //Here we remove our modified matrix to get the original one
        }
}
于 2011-10-02T16:02:00.940 回答
0

I always learnt that you should use projection matrix for perspective, not the camera (compare OpenGL FAQ). So I would set the projection (perspective) with GLU once and not change it anymore. In your draw routine you can set the camera (translate) before every draw or use glPushMatrix and glPopMatrix to safe and restore the camera.

于 2011-10-03T19:31:43.193 回答