three.js 检测两个物体是否相交(触发检测)

独自空忆成欢 提交于 2019-12-02 08:42:43

由于使用unity和UE4比较多,很多时候会用到触发检测这个功能,意思就是两个物体穿透的时候可以检测到,并做相应的操作,于是在three.js找了一大圈,最后在官方文档看到了相应的API,下面来讲述一下:

思路其实就是如果两个物体互相穿透,我们就给每个物体建一个包围盒,并把包围盒绑定物体,然后使用包围盒判断相交的api来实现,下面看看代码吧:

var scene, renderer, camera;
var redBox, blueBox, redBbox, blueBbox;
var controls;

init();
animate();

function init()
{
	renderer = new THREE.WebGLRenderer( {antialias:true} );
	var width = window.innerWidth;
	var height = window.innerHeight;
	renderer.setSize (width, height);
	document.body.appendChild (renderer.domElement);

	scene = new THREE.Scene();
	
	camera = new THREE.PerspectiveCamera (45, width/height, 1, 10000);
	camera.position.y = 50;
	camera.position.z = 50;
	camera.position.x = 50;
	camera.lookAt (new THREE.Vector3(0,0,0));

  controls = new THREE.OrbitControls (camera, renderer.domElement);
  
  redBox = new THREE.Mesh(
    new THREE.BoxGeometry(3, 3, 3),
    new THREE.MeshBasicMaterial({color: 0xff00000})//RED box
  );
  
  redBbox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());
  redBbox.setFromObject(redBox);
  const redBoxHelper = new THREE.BoxHelper(redBox, 0xFFFFFF);
  scene.add(redBbox);
  redBox.add(redBoxHelper);

	redBox.position.set(3, 3, 3);

  scene.add(redBox);

  blueBox = new THREE.Mesh(
    new THREE.BoxGeometry(3, 2, 5),
    new THREE.MeshBasicMaterial({color: 0x00000ff})//BLUE box
  );
  blueBbox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());
  blueBbox.setFromObject(blueBox);
  const blueBoxHelper = new THREE.BoxHelper(blueBox, 0xFFFFFF);
	scene.add(blueBbox);
  blueBox.add(blueBoxHelper);
  
  blueBox.position.set(3, 3, 3);
  
  scene.add(blueBox);
	
	window.addEventListener ('resize', onWindowResize, false);
}

function onWindowResize ()
{
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
	renderer.setSize (window.innerWidth, window.innerHeight);
}

function animate()
{
	//controls.update();
  requestAnimationFrame ( animate );
  
  redBox.position.x = Math.sin(Date.now() * 0.001) * 5;
  redBbox.setFromObject(redBox);
  blueBbox.setFromObject(blueBox);
  
  if(redBbox.intersectsBox(blueBbox)){
  	//两个物体相交了
         console.log("相交");
  }
  else{
  	 console.log("不相交");
  }
  
	renderer.render (scene, camera);
}

具体代码就是上面这些了,如果你想更加精细一点,类似unity或者虚幻4那样,有进入,停留,出去三个事件的话,可以添加一个开关,就是一个布尔变量控制一下

if(this.redBbox.intersectsBox(this.blueBbox)){
		 
		  if(isenter==true){
			  console.log("停留");
		  }else{
			   console.log("进入");
		  }
		   isenter=true;
		 
	  }else{
		  if(isenter==true){
			console.log("出去");
			isenter=false;
		  }
		  
	  }

isenter在外面自己定义一下,如果这个文章对你有用,给我点赞吧

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!