概要
根據像旋轉三角形這樣的預設程序使對象移動對於獲得某些注意力非常有用,但如果您希望讓用戶與OpenGL ES圖形進行交互,該怎麼辦?讓您的OpenGL ES應用程序觸摸交互的關鍵是擴展您的實現 GLSurfaceView以覆蓋 onTouchEvent()偵聽觸摸事件。
本課向您介紹如何偵聽觸摸事件以讓用戶旋轉OpenGL ES對象。
設置一個觸摸監聽器
爲了使您的OpenGL ES應用程序響應觸摸事件,您必須onTouchEvent()在您的GLSurfaceView課堂上實施該 方法 。下面的示例實現顯示瞭如何偵聽 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()以告訴渲染器該渲染幀的時間。這種方法在這個例子中是最高效的,因爲除非輪換髮生變化,否則不需要重畫框架。但是,它對效率沒有任何影響,除非您還請求渲染器僅在數據更改時使用該setRenderMode() 方法進行重繪,因此請確保在渲染器中取消註釋此行:
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對的代碼:
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
public volatile float mAngle;
public float getAngle() {
return mAngle;
}
public void setAngle(float angle) {
mAngle = angle;
}
}
應用旋轉
要應用觸摸輸入生成的旋轉,請註釋生成角度和添加的代碼mAngle,其中包含觸摸輸入生成的角度:
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);
}
完成上述步驟後,運行程序並在屏幕上拖動手指以旋轉三角形:
圖1.通過觸摸輸入旋轉的三角形(圓圈顯示觸摸位置)。
Lastest Update:2018.04.25
聯繫我
QQ:94297366
微信打賞:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ
公衆號推薦: