Threejs 通过 THREE.Box3 实现碰撞检测

根据官方文档:https://threejs.org/docs/#api/en/math/Box3.intersectsSphere

Class 1: 我需要操作的物体
protected init () {
  // 创建一个正方体
  let geometry = new THREE.BoxGeometry(0.1, 0.025, 0.05, 1, 1, 1);
  let material = new THREE.MeshPhongMaterial( { color: 0x000000, transparent: true});
  this.crashObject = new THREE.Mesh(geometry, material);
  // @ts-ignore
  this.crashObject.material.opacity = 0.5;
  this.crashObject.position.z = GameConfig.i.shipZDis;

  // 创建他的包围盒的辅助线
  this.boxHelper = new THREE.BoxHelper(this.crashObject, 0xff0000 );
  // 创建包围盒
  this.box3d = new THREE.Box3().setFromObject( this.crashObject );
  this.add(this.crashObject, this.boxHelper);
}

  // 在改变坐标的时候 及时的更新box3d 和 boxHelper的坐标

public refreshCrashObjectPos (x: number, y: number) {
    this.crashObject.position.x = x;
    this.crashObject.position.y = y;
    this.box3d.setFromObject(this.crashObject);
    this.boxHelper.update();
}

Class 2:需要检测碰撞的物体

   同样记得创建包围盒 和 辅助线

let geometry = new THREE.SphereGeometry(0.01, 16, 16);

let material = new THREE.MeshPhongMaterial( { map: texture, transparent: true, side: THREE.DoubleSide});

this.stone = new THREE.Mesh( geometry, material);

let startX = GameMgr.i.getRandomFloat(-GameConfig.i.stoneStartX, GameConfig.i.stoneStartX);

let startY = GameMgr.i.getRandomFloat(-GameConfig.i.stoneStartY, GameConfig.i.stoneStartY);

this.stone.position.x = startX; this.stone.position.y = startY;

this.stone.position.z = GameConfig.i.stoneStartZ;

this.box3d = new THREE.Box3().setFromObject(this.stone);

this.boxHelper = new THREE.BoxHelper( this.stone , 0xff0000 );

this.add(this.stone, this.boxHelper);

 

3:在检测碰撞用 调用 包围盒检测是否碰撞

let crashBox = this.crashObject.box3d;
for (let i = 0; i < this.stoneList.length; i ++) {
    let oneStone = this.stoneList[i];
    if(oneStone) {
        let stoneBox = oneStone.box3d;
        let flag = crashBox.intersectsBox(stoneBox);
        if(flag) {

                    // 撞到了

                 }

          }

}

 

 

 

 

 

 

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值