OpenGL ES|用户交互

使用预设程序使物体移动,比如旋转三角形对吸引用户注意非常有用,但是如果想让OpenGL ES图形与用户交互又该怎么做呢?让OpenGL ES 应用能响应触摸交互的关键是继承GLSurfaceView并重写OnTouchEvent()监听触摸事件.

本课将向你展示如何监听触摸事件让用户旋转OpenGL ES的物体.

设置触摸监听

为了让OpenGL ES应用响应触摸事件,你必须实现 GLSurfaceView的onTouchEvent()方法.下面的示例代码展示了如何监听 MotionEvent.ACTION_MOVE 事件,并对图形做旋转变换:

private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private float mPreviousX;
private float mPreviousY;

@Override
public boolean onTouchEvent(MotionEvent e) {
    // MotionEvent reports input details from the touch screen
    // and other input controls. In this case, you are only
    // interested in events where the touch position changed.

    float x = e.getX();
    float y = e.getY();

    switch (e.getAction()) {
        case MotionEvent.ACTION_MOVE:

            float dx = x - mPreviousX;
            float dy = y - mPreviousY;

            // reverse direction of rotation above the mid-line
            if (y > getHeight() / 2) {
              dx = dx * -1 ;
            }

            // reverse direction of rotation to left of the mid-line
            if (x < getWidth() / 2) {
              dy = dy * -1 ;
            }

            mRenderer.setAngle(
                    mRenderer.getAngle() +
                    ((dx + dy) * TOUCH_SCALE_FACTOR));
            requestRender();
    }

    mPreviousX = x;
    mPreviousY = y;
    return true;
}

注意:计算旋转角度后,会调用requestRender()方法告诉renderer渲染当前帧.示例中的这种方式是最高效的,因为你不需要重新绘制,除非发生旋转变化.然而,如果你想不影响性能,还必须使用setRenderMode()方法来告诉renderer只有在数据发生变化时才重绘,所以确保rendere中的代码取消了注释:

public MyGLSurfaceView(Context context) {
    ...
    // Render the view only when there is a change in the drawing data
    setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}

角度的操作(设置和获取)

上面的示例代码需要你在renderer中添加公开的成员变量.一旦你的rederer代码运行在与主线程分开的单独的线程中,必须将公开变量声明为 volatile.下面的代码声明 变量并提供一对getter和setter方法:

public class MyGLRenderer implements GLSurfaceView.Renderer {
    ...

    public volatile float mAngle;

    public float getAngle() {
        return mAngle;
    }

    public void setAngle(float angle) {
        mAngle = angle;
    }
}

应用投影

注释随机生成的角度,应用触摸输入生成的角度:

public void onDrawFrame(GL10 gl) {
    ...
    float[] scratch = new float[16];

    // Create a rotation for the triangle
    // long time = SystemClock.uptimeMillis() % 4000L;
    // float angle = 0.090f * ((int) time);
    Matrix.setRotateM(mRotationMatrix, 0, mAngle, 0, 0, -1.0f);

    // Combine the rotation matrix with the projection and camera view
    // Note that the mMVPMatrix factor *must be first* in order
    // for the matrix multiplication product to be correct.
    Matrix.multiplyMM(scratch, 0, mMVPMatrix, 0, mRotationMatrix, 0);

    // Draw triangle
    mTriangle.draw(scratch);
}

完成上面所有步骤,运行程序然后在屏幕上移动手指来旋转三角形:




猜你喜欢

转载自blog.csdn.net/l491337898/article/details/80047503