I've got my 2D/3D conversion working perfectly, how to do perspective

Posted by user346992 on Stack Overflow See other posts from Stack Overflow or by user346992
Published on 2010-05-21T11:36:50Z Indexed on 2010/05/21 11:40 UTC
Read the original article Hit count: 321

Filed under:
|
|
|
|

Although the context of this question is about making a 2d/3d game, the problem i have boils down to some math. Although its a 2.5D world, lets pretend its just 2d for this question.

// xa: x-accent, the x coordinate of the projection
// mapP: a coordinate on a map which need to be projected
// _Dist_ values are constants for the projection, choosing them correctly will result in i.e. an isometric projection 
xa = mapP.x * xDistX + mapP.y * xDistY; 
ya = mapP.x * yDistX + mapP.y * yDistY;

xDistX and yDistX determine the angle of the x-axis, and xDistY and yDistY determine the angle of the y-axis on the projection (and also the size of the grid, but lets assume this is 1-pixel for simplicity).

x-axis-angle = atan(yDistX/xDistX)
y-axis-angle = atan(yDistY/yDistY)

a "normal" coordinate system like this

--------------- x
|
|
|
|
|
y

has values like this:
xDistX = 1;
yDistX = 0;
xDistY = 0;
YDistY = 1;

So every step in x direction will result on the projection to 1 pixel to the right end 0 pixels down. Every step in the y direction of the projection will result in 0 steps to the right and 1 pixel down. When choosing the correct xDistX, yDistX, xDistY, yDistY, you can project any trimetric or dimetric system (which is why i chose this).

So far so good, when this is drawn everything turns out okay. If "my system" and mindset are clear, lets move on to perspective. I wanted to add some perspective to this grid so i added some extra's like this:

camera = new MapPoint(60, 60);
dx = mapP.x - camera.x; // delta x
dy = mapP.y - camera.y; // delta y
dist = Math.sqrt(dx * dx + dy * dy); // dist is the distance to the camera, Pythagoras etc.. all objects must be in front of the camera

fac = 1 - dist / 100; // this formula determines the amount of perspective

xa = fac * (mapP.x * xDistX  + mapP.y * xDistY) ;
ya = fac * (mapP.x * yDistX + mapP.y * yDistY );

Now the real hard part... what if you got a (xa,ya) point on the projection and want to calculate the original point (x,y). For the first case (without perspective) i did find the inverse function, but how can this be done for the formula with the perspective. May math skills are not quite up to the challenge to solve this.

( I vaguely remember from a long time ago mathematica could create inverse function for some special cases... could it solve this problem? Could someone maybe try?)

© Stack Overflow or respective owner

Related posts about 2d

Related posts about 3d