开发者

Detect user's touches over an OpenGL square [duplicate]

This question already has answers here: Closed 10 years ago.

Possible Duplicate:

How do I determine what is touched in 3D space from the screen?

I'm developing an Android application. I'm also working with OpenGL graphics.

I have a square drawn on the screen and I wa开发者_高级运维nt to let user move it when he touches over it. In other words, user should be able to move square when he puts his finger on the square. If he touches outside the square nothing happens.

How can I detect when user touches over square?

Thanks.


Detect touches can be implemented using ray picking. I had the same problem and I used code on this page: Android OpenGL ES ray picking. Method getViewRay() calculate the direction of ray. If you know the direction from [0,0,0] to ray[x,y,z], it is quite easy to simulate ray cast and detect the collision with bounding object.


The picking and selection tutorials supplied in other answers aren't applicable here; amongst other glSelectBuffer and glRenderMode aren't part of OpenGL ES.

There are, as stated elsewhere, essentially two approaches. You can figure out how the touch maps into your scene and test your objects mathematically. If your square is flat on, as though you were drawing it in 2d, then you can achieve that quite easily.

Alternatively, you can do something essentially like picking but adapted for the functionality available under OpenGL ES. For example, clear your scene to black and draw your square in solid blue. Use glReadPixels to get the colour value at the touch location. If it's blue then the touch is on the square. This is probably a more expensive way to test because it means an additional draw of the scene, but it means that you don't have to implement any additional maths or other code beyond what GL supplies.

The only slight thing to keep in mind is that OpenGL uses the same way of addressing pixels everywhere — (0, 0) is the bottom left, positive y goes up and positive x goes left. So whatever axes you have your touch coordinates relative to, you need to transform them to be relative to that before doing the glReadPixels.


If you have just a square you could check if the touch coordinates lie inside the space formed by the four vertexes of the square. In the case of an nonparallel to the x axis square, you shall project its vertexes using the projection matrix.

More in general there are several techniques to 'pick' an OpenGL model: ray picking and color picking being the most used. Be sure to have a look at this doc

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜