Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scale 2d world with 3d rendering?

Tags:

c++

opengl

I'm using 3d mode to render my 2d game, because the camera rotation and zooming in/out is much easier than with 2d mode.

Now i have ran into a problem i cant seem to think how to fix:

  • How to make the 2d plane of my world to fit the screen in a way that 1 texture pixel matches 1 pixel on my screen? In other words: how do i calculate the z-position of my camera to achieve this?

My texcoords start from 0 and ends to 1, so i can see all the pixels from one tile in the GL_NEAREST texture filter mode.

My window is resizeable in a way that my tiles are always squares but the visible area expands depending on how i resize my window.

Edit: my view port is using perspective mode, not isometric. but if its not possible in perspective mode, im willing to change to isometric.

like image 798
Rookie Avatar asked Nov 04 '22 05:11

Rookie


1 Answers

Use an orthographic projection that maps eye space units to pixels:

glViewport(0,0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, -1, 1);

Update due to question update:

A texel → viewport pixel matching is possible with a perspective projection, but only under a certain constraint: The textured quad must be coplanar to the perspective frustum near/far plane.

How to do it? For glFrustum(left, right, bottom, top, near, far) with Z=near, XY eye space range [left, right]×[bottom, top] maps to NDC xy[-1, 1]² and NDC xy[-1, 1]² maps to the viewport extents. So those are all affine transformations following the law

y(x) = to_lower_bound + (x - from_lower_bound) * (to_upper_bound - to_lower_bound) / (from_upper_bound - from_lower_bound)

All you have to do it map viewport to NDC to near plane and if you're Z =/= near scale by near/Z.

like image 105
datenwolf Avatar answered Nov 09 '22 11:11

datenwolf