Search code examples
javascriptmathwebglcollision

vec3.unproject() mouse collision problems


var fNearZ  = -100.0;
var farZ    = 100.0;
var fZoom   = 10.0;
var iR      = this.iWidth/fZoom;
var iL      = (this.iWidth/fZoom)*(-1);
var iT      = this.iHeight/fZoom;
var iB      = (this.iHeight/fZoom)*(-1);

var pMatrix     = new mat4.ortho(iL, iR, iB, iT, fNearZ, farZ);
var mvMatrix    = new mat4.create();

mat4.identity(mvMatrix);
zI.debug(mat4.str(mvMatrix),{'grp':'mv_before','style':'color:#060;'});

mat4.translate(mvMatrix, [0.0, 0.0, -50.0]);
mat4.scale(mvMatrix, [3, 3, 3]);

zI.debug(vec3.unproject([
        parseFloat(this.pLastMouse.x-this.iLeft),
        parseFloat(this.pLastMouse.y-this.iTop),
        0
    ],
    mvMatrix,
    pMatrix,
    [
        0,
        0,
        this.iWidth,
        this.iHeight
    ]),{'grp':'dest____','style':'color:#00F;'});

this.setMatrices(pMatrix, mvMatrix);
//After this line, buffers will be set

Screen of 16x16 Planes with 0.1 offset between SCREEN URL: https://i.sstatic.net/au2ac.png

Today I've tried to realize my mouse-collision with the new version of gl-matrix, providing vec3.unproject. What I want is to get the z-world-coordinate of the mouse-position. As you can see on the Screenshot, the x and y coordinates are ok, but the z-coordinate is always 50, no matter where the cursor befinds.

Each of the planes is 1.0x1.0 with 0.1 space between.

When I add rotation or translation on the Y-Axis, I'm receiving wrong(?) x- and y- coordinates from unproject. I think the way I handle mvMatrix and pMatrix is wrong. Can anyone please help me?

EDIT Without using .translate() and .scale() functions I'm getting the correct values of zNear and zFar right now, still don't know if the coordinates are correct, when I apply these functions to the modelview-matrix. What's still missing is the intersection-calculation.

Link to my source: http://jsfiddle.net/matthoz/vucAq/


Solution

  • The problem is that the "z-world-coordinate of the mouse-position" it's not a coordinate but an infinite amount of them (the imaginary line that shoots from the x,y position of the mouse). I'm guessing 50 it's an arbitrary value or the 50.0 you've got on the mvMatrix.

    If you make two unproject calls with zFar and zNear you will get a finite rect which you can start to work on.