DEV Community

Cover image for Using Linear Interpolation to map android touch screen values to OpenGL's coordinate system
Tristan Elliott
Tristan Elliott

Posted on

Using Linear Interpolation to map android touch screen values to OpenGL's coordinate system

Table of contents

  1. The code
  2. What we are trying to do
  3. Non-formal definition
  4. Linear Interpolation
  5. Point slope form and equations

My app on the Google play store

My app's GitHub code

Resources

The equation simplified in Kotlin

 override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        // Get screen dimensions
        val width = width.toFloat()
        val height = height.toFloat()

        // Convert screen coordinates to OpenGL coordinates
        val glX = (2.0f * event.x / width) - 1.0f
        val glY = 1.0f - (2.0f * event.y / height)
}

Enter fullscreen mode Exit fullscreen mode

What we are trying to do

  • So, I need to be able to convert Android's pixel based grid system to OpenGL's coordinate system. This will allow my user to interact with a ping pong game I created in OpenGL. Below is the feature where my user can watch their streams and play ping pong against an AI.

ping pong feature

Non-formal definition

  • As it turns out, As long as we have the boundaries of the two graphs. We can map values between them using Linear Interpolation

Linear Interpolation

  • Apple's definition of linear interpolation: Linear interpolation is a method of calculating intermediate data between known values by conceptually drawing a straight line between two adjacent known values
  • Which, is really just a fancy way to say, if we have two points, we can find the slope and if we have the slope we can find the next point. This really means that we can use the Point Slope Form(y−y1=m(x−x 1 ​)) to derive our equation.

Point slope form and equations

  • y−y1=m(x−x1)
  • (𝑥1,𝑦1) is a known point. m is the slope of the line and 𝑥 and y are any arbitrary points on the line.
  • Because linear interpolation is essentially finding points along a straight line and the point-slope form describes a straight line given a known point and a slope. We can derive the interpolation formula from the point slope. Like so:

slope interpolation formula

  • Then we can sub in the two overlapping points [0,width] and [-1,1] to simplify and get the equation for the X value:

simplified X

  • Then For the Y values we can we can sub in the two overlapping points [0,height] and [1,-1] to simplify and get the equation for the Y value:

Simplified Y

  • The x and y in the equations are the values from the android system telling us where the user clicks

Conclusion

  • Thank you for taking the time out of your day to read this blog post of mine. If you have any questions or concerns please comment below or reach out to me on Twitter.

Top comments (0)