Converting SDL Coordinates to OpenGL Coordinates

Unfortunately SDL and OpenGL use different coordinate systems. SDL takes the more traditional approach with the origin (0, 0) at the top left of the screen with the positive Y axis pointing downward. OpenGL on the other hand uses left handed screen space coordinates with the origin (0, 0) starting at the bottom left of the screen with the positive Y axis pointing upward. This can be a problem if you render something with OpenGL that you want to “click” on such as menu text. If you use SDL’s SDL_GetMouseState, the X and Y position are returned in SDL coordinates, yet your text is rendered in OpenGL coordinates. Luckily, it’s a pretty simple conversion. Both SDL and OpenGL have the same X coordinates so we only have to worry about the Y coordinate:

// Switch mousePosition to OpenGL coordinates:
mousePosition.y = windowHeight - mousePosition.y;

Yep, that’s it! Simply take the height of your window and subtract the mouse Y position. You think with such a simple conversion this would be easy to figure out. Maybe I’m dumb or I’m just not very good with math, because this took me an entire day to figure out through trial and error. Let me know in the comments section if this quick article helped you out! Later I’ll upload a quick test app to demonstrate.

Comments

No comments, yet!


Login or Sign up to post comments!


<< previous| | next >>