我跟着this article on MDN检测了盒子之间的碰撞,并在this JSFiddle中尝试了它。
我希望能够移动红色框,当它们不再碰撞时,我希望日志停止出现......但是,我不知道如何保留Box3(我的盒子的边界框) )更新到我主箱的新位置。
我目前用键盘键移动盒子,如下所示:
检查是否按下了键
switch (e.key) {
case `z`:
moveForward = true;
break;
case `s`:
moveBackward = true;
break;
case `q`:
moveLeft = true;
break;
case `d`:
moveRight = true;
break;
}
在我的动画功能中:
if (moveForward) redBox.position.z -= .05;
if (moveBackward) redBox.position.z += .05;
if (moveLeft) redBox.position.x -= .05;
if (moveRight) redBox.position.x += .05;
我会猜到简单的解决方案是更新Box3的位置,但似乎我不允许将Box3添加到我的场景......所以我不知道如何更新它。 / p>
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
);
redBox.position.set(3, 3, 3);
redBbox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());
redBbox.setFromObject(redBox);
const redBoxHelper = new THREE.BoxHelper(redBox, 0xFFFFFF);
scene.add(redBox, redBoxHelper);
blueBox = new THREE.Mesh(
new THREE.BoxGeometry(3, 2, 5),
new THREE.MeshBasicMaterial({color: 0x00000ff})//BLUE box
);
blueBox.position.set(3, 3, 3);
blueBbox = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3());
blueBbox.setFromObject(blueBox);
const blueBoxHelper = new THREE.BoxHelper(blueBox, 0xFFFFFF);
scene.add(blueBox, blueBoxHelper);
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 );
if(redBbox.intersectsBox(blueBbox)){
console.log('intersection');
}
renderer.render (scene, camera);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r83/three.min.js"></script>
<script src="https://dl.dropboxusercontent.com/u/3587259/Code/Threejs/OrbitControls.js">
</script>
答案 0 :(得分:2)
根据MDN文章的示例,在检查交叉点之前,在您的animation()
函数中添加下两行:
redBbox.setFromObject(redBox);
blueBbox.setFromObject(blueBox);
jsfiddle示例。