3

这个问题有很多答案,但我不确定它们是否都适用于 XTK,例如在 Three.JS 中看到多个答案,但当然 XTK 和 Three.JS 显然没有相同的 API。使用射线并且Matrix似乎与其他框架的许多其他解决方案非常相似,但我仍然没有在这里掌握可能的解决方案。现在只需找到坐标 X、Y 和 Z 并将它们记录下来Console.Log就可以了,后来我希望创建一个标题/工具提示来显示信息,但还有其他方法可以显示它。但是至少有人可以告诉我这是否可以使用射线与物体碰撞?我不确定在 XTK 中如何与网格或任何其他文件发生碰撞。现在的任何提示都会很棒!

4

2 回答 2

4

这是我在 xtk 中取消投影的功能。如果您发现错误,请告诉我。现在有了结果点和相机位置,我应该能够找到我的交叉点。为了使后续步骤的计算更快,我将在选择事件中调用它,因此我只需要尝试与给定对象的交集。如果我有时间,我也会尝试测试边界框。

注意事项:最后几行不是必需的,我可以在射线而不是点上工作。

X.camera3D.prototype.unproject = function (x,y) {

  // get the 4x4 model-view matrix
  var mvMatrix = this._view;

  // create the 4x4 projection matrix from the flatten gl version
  var pMatrix = new X.matrix(4,4);
  for (var i=0 ; i<16 ; i++) {
    pMatrix.setValueAt(i - 4*Math.floor(i/4), Math.floor(i/4), this._perspective[i]);
  }
  // compute the product and inverse it
  var mvpMatrxix = pMatrix.multiply(mwMatrix); /** Edit : wrong product corrected **/
  var inverse_mvpMatrix = mvpMatrxix.getInverse();
  if (!goog.isDefAndNotNull(inverse_mvpMatrix)) throw new Error("Could not inverse the transformation matrix.");

  // check if x & y are map in [-1,1] interval (required for the computations)
  if (x<-1 || x>1 || y<-1 || y>1) throw new Error("Invalid x or y coordinate, it must be between -1 and 1");

  // fill the 4x1 normalized (in [-1,1]⁴) vector of the point of the screen in word camera world's basis
  var point4f = new X.matrix(4,1);
  point4f.setValueAt(0, 0, x);
  point4f.setValueAt(1, 0, y);
  point4f.setValueAt(2, 0, -1.0); // 2*?-1, with ?=0 for near plan and ?=1 for far plan
  point4f.setValueAt(3, 0, 1.0); // homogeneous coordinate arbitrary set at 1

  // compute the picked ray in the world's basis in homogeneous coordinates
  var ray4f = inverse_mvpMatrix.multiply(point4f);
  if (ray4f.getValueAt(3,0)==0) throw new Error("Ray is not valid.");
  // return in not-homogeneous coordinates to compute the 3D direction vector
  var point3f = new X.matrix(3,1);
  point3f.setValueAt(0, 0, ray4f.getValueAt(0, 0) / ray4f.getValueAt(3, 0) );
  point3f.setValueAt(1, 0, ray4f.getValueAt(1, 0) / ray4f.getValueAt(3, 0) );
  point3f.setValueAt(2, 0, ray4f.getValueAt(2, 0) / ray4f.getValueAt(3, 0) );
  return point3f;
};

编辑

在这里,在我的 repo 中,您可以在 camera3D.js 和 renderer3D.js 中找到用于在 xtk 中进行高效 3D 拾取的函数。

于 2012-07-23T10:23:24.420 回答
2

现在这不容易。我想你可以抓住相机的视图矩阵来计算位置。如果您这样做,最好将其作为内置功能带回 XTK!

目前,只能像这样选择对象(r 是 X.renderer3D):

/**
* Picks an object at a position defined by display coordinates. If
* X.renderer3D.config['PICKING_ENABLED'] is FALSE, this function always returns
* -1.
*
* @param {!number} x The X-value of the display coordinates.
* @param {!number} y The Y-value of the display coordinates.
* @return {number} The ID of the found X.object or -1 if no X.object was found.
*/
var pick = r.pick($X, $Y);
于 2012-07-18T13:21:56.133 回答