根据官方文档: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) {
// 撞到了
}
}
}