使对象根据预设的程序进行运动,比如旋转三角形,可以吸引人的注意力。但是如果你想让用户同你的OpenGL ES图形进行交互会怎么样呢?使你的OpenGL ES应用程序触摸互动的关键是要扩展GLSurfaceView,复写onTouchEvent()方法,来监听touch事件。本教程展示了,如何监听透出事件,让用户旋转一个OpenGL ES对象。
1. 设置一个Touch Listener
为了使你的OpenGL ES应用响应touch事件,你必须在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需要渲染该帧,在本例中的这种途径是最优效的,因为帧只有在角度更改的时候才会重新绘制。但是,当你设置了渲染模式为RENDERMODE_WHEN_DIRTY的时候才会提高效率,所以确保renderer中该行的代码是没有被注释掉的:
public MyGLSurfaceView(Context context) {
...
// Render the view only when there is a change in the drawing data
setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
}
2. public旋转角度
上面的示例代码需要你通过添加public成员来暴露旋转角度参数。因为renderer代码是运行在一个独立于主线程的线程里面,所以你必须声明该参数为volatile:
public class MyGLRenderer implements GLSurfaceView.Renderer {
...
public volatile float mAngle;
public float getAngle() {
return mAngle;
}
public void setAngle(float angle) {
mAngle = angle;
}
}
3. 应用角度
为了应用touch输入产生的角度,注释掉产生调度的代码,添加由touch输入产生的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);
}
当你完成了上面描述的步骤,执行代码,就可以在屏幕上拖动手指来旋转这个三角形了。
原文地址 : http://developer.android.com/training/graphics/opengl/touch.html#angle