使用預設程序使物體移動,比如旋轉三角形對吸引用戶注意非常有用,但是如果想讓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);
}
完成上面所有步驟,運行程序然後在屏幕上移動手指來旋轉三角形: