在three.js中使用相机进行碰撞检测(光线投射)

时间:2020-06-15 12:02:18

标签: three.js collision-detection raycasting

我使用3.js将3d模型.obj上传到网站。我需要相机不要穿过该模型的墙壁。我尝试通过Raycaster.intersectObjects防止这种情况。但是,使用Raycaster的这部分代码不起作用。 3D模型是一个有地板和墙壁的房间,我使用OrbitControls进行导航。我不明白我在做什么错。 请问你能帮帮我吗?我是Three.js的新手。

var controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.25;
controls.enableZoom = false;
controls.keys = {
	LEFT: 37, //left arrow
	UP: 38, // up arrow
	RIGHT: 39, // right arrow
	BOTTOM: 40 // down arrow
}


var objects = [];

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setTexturePath('/assets/');
mtlLoader.setPath('/assets/');
mtlLoader.load('GALLERY_EXPORT.mtl', function (materials) {
    materials.preload();
    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.setPath('/assets/');
    objLoader.load('GALLERY_EXPORT.obj', function (object) {
    object.traverse(function(node){
				if( node instanceof THREE.Mesh ){
					node.castShadow = true;
					node.receiveShadow = true;
				}
			});
        scene.add(object);
        object.position.y = 0;
        object.position.z = 500;
        object.position.x = 1500;

         objects.push( object );
      });
});


var castRays = function () {
var cameraForwardDirection = new THREE.Vector3(0,0,-1).applyMatrix4(camera.matrixWorld);
var ray = new THREE.Raycaster(camera.position, cameraForwardDirection);
var intersects = ray.intersectObject(scene.children, true);
if(intersects.length>0){
 controls.moveForward=false;
}
}
castRays();

0 个答案:

没有答案