Search code examples
javascript3dprojectionhtml5-canvas

Projecting a 3D point to a 2D point makes things get inverted


It seems everything in back of the camera get's inverted back or something: current screenshot

This is the original model: original model

So the camera is in the right opening of the "frame".

Here's the depth calculation (I think the problem is here):

function 3dto2d(x, y, z) {
    var scale = cameradistance / (cameradistance - z);
    return {
        'x' : x * scale,
        'y' : y * scale
    };
}

Does someone know this problem?

EDIT: I have the answer here:

function 3dto2d(x, y, z) {
    var scale = cameradistance / (cameradistance - (z >= cameradistance ? cameradistance - 1 : z));
    return {
        'x' : x * scale,
        'y' : y * scale
    };
}

Solution

  • This also happened to me when points have a z <= 0, because then the projection formulas are invalid. Just don't rotate your object in such a way that points get z <= 0.

    It's inverted because the formula y = 1 / x is point symmetric around the origin. So for x <= 0 then y becomes -y. E.g., 1 / 2 = 1 / 2, but 1 / -2 = - 1 / 2.

    To come to the point, I'd say you'd be best off altering your engine so as to map values z <= 0 to z = 1 (or something smaller). Though this is a cheap trick, of course. There are probably more meaningful techniques for this.