android opengl 点击,Android---OpenGL ES之响应触屏事件

像旋转三角形那样,让对象根据预设的程序来移动,以便有助于获取人们的关注,但是如 果想要让你的OpenGL ES图形跟用户交互,应该怎样做呢?要让你的OpenGL ES应用程序能够触碰交互的关键是扩展你的GLSurfaceView实现,重写它的onTouchEvent()方法来监听触碰事件。

本文介绍如何监听触碰事件,让用户可以旋转OpenGL ES对象。

设置触碰监听器

为了让你的OpenGL ES应用程序响应触碰事件,你必须在你GLSurfaceView类中实现onTouchEvent()事件。以下实现的示例显示如何监听MotionEvent.ACTION_MOVE事件,并把它们转换成图形旋转的角度。

@Override

publicbooleanonTouchEvent(MotionEvent e) {

// MotionEvent reportsinput details from the touch screen

// and other inputcontrols. In this case, you are only

// interested in eventswhere the touch position changed.

floatx = e.getX();

floaty = e.getY();

switch(e.getAction()) {

caseMotionEvent.ACTION_MOVE:

floatdx = x - mPreviousX;

floatdy = 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 

dy = dy * -1;

}

mRenderer.mAngle += (dx + dy) * TOUCH_SCALE_FACTOR; // = 180.0f /320

requestRender();

}

mPreviousX = x;

mPreviousY = y;

returntrue;

}

注意,计算旋转的角度之后,这个方法调用了requestRender()方法来告诉渲 染器,到了渲染帧的时候了。上例中所使用的方法是最有效的,只有在有旋转变化时,帧才会被重绘。但是要想只在数据变化的时候,才请求渲染器重绘,就要使用 setRenderMode()方法来设置绘制模式。

publicMyGLSurfaceView(Context context){

...

// Render the view onlywhen there is a change in the drawing data

setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

}

暴露旋转的角度

上例代码要求你通过添加一个公共的成员变量,通过渲染器把旋转的角度暴露出来。因为渲染器代码运行在一个独立于主用户界面线程之外的线程中,所以你必须声明一个公共变量,代码如下:

publicclassMyGLRendererimplementsGLSurfaceView.Renderer{

...

publicvolatilefloatmAngle;

应用旋转

以下代码完成由触碰输入所产生的旋转:

publicvoidonDrawFrame(GL10 gl){

...

// Create a rotation forthe triangle

// long time =SystemClock.uptimeMillis() % 4000L;

// float angle = 0.090f *((int) time);

Matrix.setRotateM(mRotationMatrix, 0, mAngle,0,0, -1.0f);

// Combine the rotationmatrix with the projection and camera view

Matrix.multiplyMM(mMVPMatrix, 0, mRotationMatrix,0, mMVPMatrix,0);

// Draw triangle

mTriangle.draw(mMVPMatrix);

}

【编辑推荐】

【责任编辑:闫佳明 TEL:(010)68476606】

点赞 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值