0
\$\begingroup\$

I'm trying to implement a 2D camera in modern OpenGL.

Before I moved over to OpenGL, I used SDL to make my games and their concept of a camera is by creating a camera quad and each time the camera moves, objects is being offset by this camera quad's position, giving the effect that the game world is scrolling when the camera moves.

I have a working 3D camera at the moment, which are using a view matrix and a look at-matrix to construct the final view projection matrix, which are then sent to the shader(s). So I know the concept of an actual camera.

I have checked a few tutorials and code examples that are using a orthographic matrix to create the 2D camera, followed by calling glViewport to construct the viewport of the game. However, none of the tutorials (and such) that I've watched is using the orthographic camera and the glViewport to actually scroll the camera and are instead only using it to render HUD objects and such.

How is a scrolling 2D camera usually made in OpenGL? Using the same concept of a 2D camera as SDL uses or are the matrices used to offset the objects being affected by the 2D camera? I am having a hard time understanding the concept of a orthographic camera aswell.

\$\endgroup\$
  • 1
    \$\begingroup\$ Well, just apply a translation matrix (with negated camera coordinates) to your orthographic camera matrix. \$\endgroup\$ – HolyBlackCat Feb 6 '17 at 0:36
0
\$\begingroup\$

OpenGL represents the screen as a 2x2x2 cube (-1 to 1 on each axis). So your camera matrix needs to squish the scene into that box. The box is then stretched to size of the viewport. So make sure your conceptual camera has the same aspect ratio as your viewport otherwise it will look squished.

If your conceptual camera is 320 pixels wide then your camera matrix needs to scale the scene by a factor of 2/320. The camera's offsets have to be scaled by this factor too, which makes life difficult. The easier way is to make a camera matrix that moves the conceptual camera into place and then invert the matrix.

So if you have a 320x200 camera centered on pixel 50,60 - create a scaling matrix that scales the scene 160x100x1 and then multiply by a translation matrix of 50,60,0. Take the resulting matrix and invert it and that's the camera matrix to give OpenGL.

Also don't forget that OpenGL has y-axis up like in algebra class and not y-axis down like SDL's surfaces.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.