我在过去的6个小时内一直试图在我的webgl应用中实施点击,但我找不到任何关于此主题的明确内容。
到目前为止我想出的是伪代码:
screenSpace = mousePosition;
normalizedScreenSpace = (screenSpace.x/screen.width, screenSpace.y/screen.height);
camSpace = invertProjectionMatrix * normalizedScreenSpace;
worldSpace = invertViewMatrix * camSpace;
打印出worldSpace坐标,它与场景中的其他对象不对应。我做错了什么?
答案 0 :(得分:1)
viewProjection矩阵将vec3从世界空间带到剪辑空间,因此它的反向反转,将空间剪辑到世界空间。什么是缺少的是gpu在引擎盖后面为你处理的视角鸿沟,所以你也必须考虑到这一点。添加屏幕宽度和高度,让您的屏幕显示世界:
screenToWorld: function(invViewProjection, screenWidth, screenHeight){
// expects this[2] (z value) to be -1 if want position at zNear and +1 at zFar
var x = 2*this[0]/screenWidth - 1.0;
var y = 1.0 - (2*this[1]/screenHeight); // note: Y axis oriented top -> down in screen space
var z = this[2];
this.setXYZ(x,y,z);
this.applyMat4(invViewProjection);
var m = invViewProjection;
var w = m[3] * x + m[7] * y + m[11] * z + m[15]; // required for perspective divide
if (w !== 0){
var invW = 1.0/w;
this[0] *= invW;
this[1] *= invW;
this[2] *= invW;
}
return this;
},
反向计算:
worldToScreen: function(viewProjectionMatrix, screenWidth, screenHeight){
var m = viewProjectionMatrix;
var w = m[3] * this[0] + m[7] * this[1] + m[11] * this[2] + m[15]; // required for perspective divide
this.applyMat4(viewProjectionMatrix);
if (w!==0){ // do perspective divide and NDC -> screen conversion
var invW = 1.0/w;
this[0] = (this[0]*invW + 1) / 2 * screenWidth;
this[1] = (1-this[1]*invW) / 2 * screenHeight; // screen space Y goes from top to bottom
this[2] *= invW;
}
return this;
},