回應觸控事件

根據旋轉三角形等預設程式移動物件,可有效獲得注意力,但如果想讓使用者與您的 OpenGL ES 圖形互動,該怎麼做?讓 OpenGL ES 應用程式觸控互動的關鍵在於展開 GLSurfaceView 實作,以覆寫 onTouchEvent() 以監聽觸控事件。

本課程將說明如何監聽觸控事件,讓使用者可旋轉 OpenGL ES 物件。

設定觸控事件監聽器

為了讓 OpenGL ES 應用程式回應觸控事件,您必須在 GLSurfaceView 類別中實作 onTouchEvent() 方法。下列實作範例說明如何監聽 MotionEvent.ACTION_MOVE 事件,並將其轉譯為形狀的旋轉角度。

Kotlin

private const val TOUCH_SCALE_FACTOR: Float = 180.0f / 320f
...
private var previousX: Float = 0f
private var previousY: Float = 0f

override fun onTouchEvent(e: MotionEvent): Boolean {
    // 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.

    val x: Float = e.x
    val y: Float = e.y

    when (e.action) {
        MotionEvent.ACTION_MOVE -> {

            var dx: Float = x - previousX
            var dy: Float = y - previousY

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

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

            renderer.angle += (dx + dy) * TOUCH_SCALE_FACTOR
            requestRender()
        }
    }

    previousX = x
    previousY = y
    return true
}

Java

private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
private float previousX;
private float previousY;

@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 - previousX;
            float dy = y - previousY;

            // 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 ;
            }

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

    previousX = x;
    previousY = y;
    return true;
}

請注意,在計算旋轉角度後,這個方法會呼叫 requestRender(),向轉譯器告知轉譯影格的時間。此方法在本範例中最有效率,因為除非旋轉改變,否則不需要重新繪製影格。不過,除非您也要求轉譯器只在使用 setRenderMode() 方法變更資料時才重新繪製,否則不會影響效率,因此請確認這行程式碼在轉譯器中取消註解:

Kotlin

class MyGlSurfaceView(context: Context) : GLSurfaceView(context) {

    init {
        // Render the view only when there is a change in the drawing data
        renderMode = GLSurfaceView.RENDERMODE_WHEN_DIRTY
    }
}

Java

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

公開旋轉角度

上述範例程式碼會要求您新增公開成員,透過轉譯器公開旋轉角度。由於轉譯器程式碼是在應用程式主要使用者介面執行緒外的獨立執行緒上執行,因此您必須將此公開變數宣告為 volatile。以下程式碼可用於宣告變數,並公開 getter 和 setter 組合:

Kotlin

class MyGLRenderer4 : GLSurfaceView.Renderer {

    @Volatile
    var angle: Float = 0f
}

Java

public class MyGLRenderer implements GLSurfaceView.Renderer {
    ...

    public volatile float mAngle;

    public float getAngle() {
        return mAngle;
    }

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

套用旋轉設定

如要套用觸控輸入產生的旋轉,請將產生角度的程式碼註解排除,並新增含有觸控輸入角度的變數:

Kotlin

override fun onDrawFrame(gl: GL10) {
    ...
    val scratch = FloatArray(16)

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

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

    // Draw triangle
    triangle.draw(scratch)
}

Java

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(rotationMatrix, 0, mAngle, 0, 0, -1.0f);

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

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

完成上述步驟後,請執行程式,然後在螢幕上拖曳手指來旋轉三角形:

圖 1 使用觸控輸入旋轉的三角形 (圓形表示觸控位置)。