Search code examples
androidopengl-estouchvertices

Using Touch Coordinates in Android OpenGL Renderer


I am able draw rectangles or squares in android opengl by mentioning float values for vertices like 0.1f, 1.2f etc...

 private float vertices[] = {

       -1.0f, 0.8f,  0.0f,        // V1 - bottom left

       -1.0f, 1.0f,  0.0f,        // V2 - top left

        1.0f, 0.8f,  0.0f,        // V3 - bottom right

        1.0f, 1.0f,  0.0f         // V4 - top right

};

But i want to draw shapes(rectangle) where my user touches... for example if user touches at (x,y) =(200px,300px).

I want to draw a small rectangle there... but when i pass these values into the vertices the rectangle goes outside my screen....

Can anyone help me understand how to accomplish this.

Thanks.


Solution

  • Your touch coordinates come in screen coordinates, which are pixel based, while in your current situation, you're rendering in what's often named normalized device coordinates, which allow you to draw in from [-1,1] in the X & Y coordinates.

    What you're missing are the transformations to make those two spaces work together. Perhaps the simplest solution for your scenario is to render in screen coordinates. Basically, take each of your touch coordinates and map it into the range [-1,1]. Something like the following should work:

    x_drawing_coordinate = 2.0 * x_touch_coordinate / screen_width - 1.0
    

    and do the same for the y-coordinate, except use the screen_height.