How to detect collision in three.js?

前端 未结 4 1945
小鲜肉
小鲜肉 2020-11-30 23:48

I am using three.js.

I have two mesh geometries in my scene.

If these geometries are intersected (or would intersect if translated) I want to detect

4条回答
  •  一整个雨季
    2020-12-01 00:17

    only works on BoxGeometry and BoxBufferGeometry

    create the following function:

    function checkTouching(a, d) {
      let b1 = a.position.y - a.geometry.parameters.height / 2;
      let t1 = a.position.y + a.geometry.parameters.height / 2;
      let r1 = a.position.x + a.geometry.parameters.width / 2;
      let l1 = a.position.x - a.geometry.parameters.width / 2;
      let f1 = a.position.z - a.geometry.parameters.depth / 2;
      let B1 = a.position.z + a.geometry.parameters.depth / 2;
      let b2 = d.position.y - d.geometry.parameters.height / 2;
      let t2 = d.position.y + d.geometry.parameters.height / 2;
      let r2 = d.position.x + d.geometry.parameters.width / 2;
      let l2 = d.position.x - d.geometry.parameters.width / 2;
      let f2 = d.position.z - d.geometry.parameters.depth / 2;
      let B2 = d.position.z + d.geometry.parameters.depth / 2;
      if (t1 < b2 || r1 < l2 || b1 > t2 || l1 > r2 || f1 > B2 || B1 < f2) {
        return false;
      }
      return true;
    }
    

    use it in conditional statements like this:

    if (checkTouching(cube1,cube2)) {
    alert("collision!")
    }
    

    I have an example using this at https://3d-collion-test.glitch.me/

    Note: if you rotate(or scale) one (or both) of the cubes/prisims, it will detect as though they haven't been turned(or scaled)

提交回复
热议问题