【问题标题】:ThreeJS | Detect when an object leaves another object三JS |检测一个物体何时离开另一个物体
【发布时间】:2020-05-21 14:51:28
【问题描述】:

我正在制作一个 ThreeJS 项目,其中有 planes (Object3D)sphere (Mesh) 内飞行。

我正在尝试检测平面与球体边界之间的碰撞,以便删除该平面并使其重新出现在球体内部的另一个位置。

我的问题是如何检测一个对象何时离开另一个对象?

我现在的代码:

detectCollision(plane, sphere) {

  var boxPlane = new THREE.Box3().setFromObject(plane);
  boxPlane.applyMatrix4(plane.matrixWorld);

  var boxSphere = new THREE.Box3().setFromObject(sphere);
  boxSphere.applyMatrix4(sphere.matrixWorld);

  return boxPlane.intersectsBox(boxSphere);

}

在我的渲染函数中:

var collision = this.detectCollision(plane, this.radar)
  if (collision == true) {
    console.log("the plane is inside the sphere")
  }
  else {
    console.log("the plane is outside the sphere")
  }
})

问题是当飞机在球体内时,我得到 truefalse 基本上所有直到所有平面离开球体为止。那时我有一个 false 并且没有更多 true

【问题讨论】:

    标签: javascript three.js collision-detection bounding-box


    【解决方案1】:

    Box3 不是您想要用来计算球体和平面碰撞的对象,因为该框不会考虑球体的曲率,也不会跟随平面的旋转。

    Three.js 有一个类 THREE.Sphere 更接近您的需要。请记住,这个类与带有SphereGeometryMesh 相同,这更像是一个不渲染到画布的数学助手。您可以根据需要使用其.containsPoint() 方法:

    var sphereCalc = new THREE.Sphere( center, radius );
    var point = new THREE.Vector3(10, 4, -6);
    
    detectCollision() {
        var collided = sphereCalc.containsPoint(point);
    
        if (collided) {
            console.log("Point is in sphere");
        } else {
            console.log("No collision");
        }
    
        return collided;
    }
    
    

    您必须应用变换并在循环中检查每个平面的所有 4 个点。请注意,有一个 Sphere.intersectsPlane() 方法听起来会为您执行此操作,但它不一样,因为它使用 infinite 平面来计算交点,而不是具有定义宽度和高度的平面,所以不要用这个。

    编辑:

    为了澄清,每个平面通常有 4 个顶点,因此您必须检查每个顶点 in a for() loop 以查看球体是否包含 4 个点中的每一个。

    此外,平面可能已被移动和旋转,因此其原始顶点位置将应用变换矩阵。我想你已经在你的例子中考虑到了这一点,但它会是这样的:

    point.copy(vertex1);
    point.applyMatrix4(plane.matrixWorld)
    sphereCalc.containsPoint(point);
    
    point.copy(vertex2);
    point.applyMatrix4(plane.matrixWorld)
    sphereCalc.containsPoint(point);
    
    // ... and so on
    
    

    【讨论】:

    • 首先感谢您的宝贵时间和良好的解释 :) 但有些不清楚:“您必须应用变换并检查每个平面的所有 4 个点循环”。你能更准确地说我应该用什么来做这件事吗? (我是 ThreeJS 的初学者)
    • 当然,我在回答中添加了说明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多