three提供两种碰撞检测
1.【射线检测【相机视线内是一条直线,这条线触碰到的物体会被检测到】】
========一般可以设置一下射线发射的位置 实时更新位置会比较准=====
let dir = new Vector3(0, 1, 0);
doc.raycaster.set(pos, dir);
========一般可以设置一下射线发射的位置 实时更新位置会比较准=====
let worldScene = new THREE.Scene()
let cameraPos = new THREE.Camera.position();
var raycaster = new THREE.Raycaster();//射线检测
var mouse = new THREE.Vector2()
raycaster.setFromCamera( mouse, camera );//设置射线
function onMouseClick(event){
//将鼠标点击位置的屏幕坐标转换成threejs中的标准坐标
mouse.x = (event.clientX/window.innerWidth)2-1
mouse.y = -((event.clientY/window.innerHeight)2-1)
//console.log("mouse:"+mouse.x+","+mouse.y)
// 通过鼠标点的位置和当前相机的矩阵计算出raycaster
raycaster.setFromCamera( mouse, camera );
// 获取raycaster直线和所有模型相交的数组集合
var intersects = raycaster.intersectObjects( worldScene.children,true);
console.log(intersects,"模型集合");
//将所有的相交的模型的颜色设置为红色
for ( var i = 0; i < intersects.length; i++ ) {
intersects[ i ].object.material.color.set( 0xff0000 );
}
}
===========================================================================
2.八叉树检测
let a1 = window.ThreeObj.doc.scene.children[3].position;//一个元素的Vector3坐标 (3维坐标 position)
let a2 = window.ThreeObj.doc.scene.children[4].position;//一个元素的Vector3坐标 (3维坐标 position)
window.ThreeObj.doc.scene.children[4].position.y-=0.02;
const playerCollider2 = new Capsule( a1, a2, 0.0000035 );
console.log("检测对象==",playerCollider2)
const result2 = worldOctree.capsuleIntersect( playerCollider2 );
console.log("当前场景",result2.depth)
当获取不到result2.depth的值时候说明碰撞了
网友评论