Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 want 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.

like image 481
VansFannel Avatar asked Nov 11 '10 12:11

VansFannel


2 Answers

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.

like image 138
petrnohejl Avatar answered Oct 15 '22 05:10

petrnohejl


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.

like image 37
Tommy Avatar answered Oct 15 '22 04:10

Tommy