Piku
Piku

Reputation: 3626

How to convert screen co-ordinates into 2D OpenGL co-ordinates

I have the following 2D orthographic projection set up on my iPad:

The iPad is landscape with its button on the left with screen co-ords like this:

How do I calculate the 2D GL position when the user touches the screen? iOS gives me the screen location where the user tapped.

I.e if I tap the screen in the middle, iOS tells me I tapped at (512,384) so this should be converted to (0,0), (1024,768) to (-1.33,1.0) etc.

I know this should be a reasonably straight forward bit of maths, but my brain's gone to mush after trying to figure it out.

Upvotes: 0

Views: 287

Answers (1)

Marcelo Cantos
Marcelo Cantos

Reputation: 186078

For a screen with dimensions w and h, mapping to [-1, -1]...[1, 1] goes like this:

X = 2*x/w - 1
Y = 1 - 2*y/h

To match the aspect ratio of the screen, multiply X by w/h.

Upvotes: 1

Related Questions