期望false时,intersectsBox返回true

时间:2016-12-18 22:44:54

标签: javascript 3d three.js

我按照MDN的说明来检查边界框的交叉点。所以我写了代码:

  const testBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const testBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  testBox = new THREE.Mesh(testBoxGeometry, testBoxMaterial);
  testBox.geometry.computeBoundingBox();
  testBoundingBox = new THREE.Box3(
    testBox.geometry.boundingBox.min,
    testBox.geometry.boundingBox.max
  );
  testBox.position.set(5, 0, 5);
  scene.add(testBox);

  const cameraBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const cameraBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  cameraBox = new THREE.Mesh(cameraBoxGeometry, cameraBoxMaterial);
  cameraBox.geometry.computeBoundingBox();
  cameraBoundingBox = new THREE.Box3(
    cameraBox.geometry.boundingBox.min,
    cameraBox.geometry.boundingBox.max
  );
  scene.add(cameraBox);

在我的动画功能中

  if (testBoundingBox.intersectsBox(cameraBoundingBox)) {
    console.log(`intersection`);
  }

正如您在此屏幕截图中看到的那样,两个绿色框不相交,但它们已经记录下来了......有人可能知道我可能做错了什么或推动我调试这个方向?

Screenshot of intersection constantly logging.

修改

正如Hectate所提到的,我应该添加setFromObject(),这解决了我最初的问题。但是,现在我遇到了一个新问题,因为我使用的第一个方块代表了我的相机。我想创建一个环境并检查播放器(模拟第一人的相机)是否与该区域中的任何对象发生碰撞。我这样做是通过制作一个Object3D()并添加相机和一个正方形。我将使该方块不可见,但使用它来检测碰撞的边界。

因为我翻译(我使用translate for performance)玩家Object3D,我的原始位置保持不变,交叉点只能OR不断发生或永远不会发生...有关如何解决这个问题的想法吗?

我用来导航我的播放器Object3D的代码:

检查是否按下了键

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) player.translateZ(- .05);
if (moveBackward) player.translateZ(.05);
if (moveLeft) player.translateX(- .05);
if (moveRight) player.translateX(.05);

编辑2

这是我的完整script.js:

import sets from './data/sets';

import ColladaLoader from 'three-collada-loader';

import BufferLoader from './modules/sound/BufferLoader';
import SpawnObject from './modules/render/SpawnObject';
import Controls from './modules/util/Controls';

import io from 'socket.io-client';
import {isEmpty} from 'lodash';

const OrbitControls = require(`./modules/util/OrbitControls`)(THREE);
const DeviceOrientationControls = require(`./modules/util/DeviceOrientationControls`);

// const PointerLockControls = require(`./modules/util/PointerLockControls`);

let scene, camera, renderer, VRcontrols, element, cameraBox, testBox, cameraBoundingBox, testBoundingBox;
let audioCtx, bufferLoader;
let socket, controlData;

let player, playerMesh;

let mobile;

let moveForward = false, moveBackward = false, moveLeft = false, moveRight = false;

let camX = 0;
const camY = 0;
let camZ = 2;

let mousedown = false;

const camSpeed = .1;

const notes = [];
let devices = [];
const collidableMeshList = [];

const mobilecheck = () => {
  mobile = false;
  (function(a) {if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) mobile = true;})(navigator.userAgent || navigator.vendor || window.opera);
  return mobile;
};

const init = () => {

  mobilecheck();

  socket = io(`/`);

  socket.on(`init`, handleWSInit);
  socket.on(`dataTransfer`, handleWSData);

  window.AudioContext = window.AudioContext || window.webkitAudioContext;

  if (!mobile) {
    document.addEventListener(`keydown`, useArrowDown);
    document.addEventListener(`keyup`, useArrowUp);
    document.addEventListener(`mousedown`, () => mousedown = true);
    document.addEventListener(`mouseup`, () => mousedown = false);
    document.addEventListener(`mousemove`, e => {
      if (mousedown) {
        const rotateAngle = Math.PI / 4;
        player.rotateY(rotateAngle * e.movementX * .1);
      }
    });
  }

};

const handleWSInit = users => {
  const {id: socketId} = socket;

  users = users.map(u => {
    if (u.socketId === socketId) u.isMe = true;
    return u;
  });

  devices = users;

  if (window.location.href.indexOf(`controls`) > - 1) {
    const controls = new Controls(socket, devices);
    console.log(controls);
    return;
  }

  document.querySelector(`main`).classList.remove(`controls`);

  loadAudio();

};

const loadAudio = () => {
  audioCtx = new AudioContext();
  bufferLoader = new BufferLoader(audioCtx);

  bufferLoader.load(sets.drums)
    .then(data => spawnObject(data));


  initEnvironment();
};

const handleWSData = data => {
  if (data !== undefined || data !== null || isEmpty(data)) controlData = data;

  devices = devices.map(u => {
    u.yo = false;
    return u;
  });

};

const spawnObject = data => {

  for (let i = 0;i < 5;i ++) {
    const bol = new SpawnObject(`object.dae`, audioCtx, data[0], scene, true);
    notes.push(bol);
    collidableMeshList.push((notes[0].scene.children[2]));

  }
};

const initEnvironment = () => {
  console.log(notes);
  scene = new THREE.Scene();
  camera = new THREE.PerspectiveCamera(
    50, window.innerWidth / window.innerHeight,
    1, 1000
  );

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  element = renderer.domElement;
  document.body.appendChild(element);

  //PLAYER
  player = new THREE.Object3D();

  const testBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const testBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  testBox = new THREE.Mesh(testBoxGeometry, testBoxMaterial);
  testBox.geometry.computeBoundingBox();
  const testBoxHelper = new THREE.BoxHelper(testBox, 0x0000ff);
  testBoundingBox = new THREE.Box3(
    testBox.geometry.boundingBox.min,
    testBox.geometry.boundingBox.max
  );
  testBox.position.set(0, 0, 3);
  testBoundingBox.setFromObject(testBox);
  scene.add(testBox);
  scene.add(testBoxHelper);
  const cameraBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const cameraBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  cameraBox = new THREE.Mesh(cameraBoxGeometry, cameraBoxMaterial);
  cameraBox.geometry.computeBoundingBox();
  const cameraBoxHelper = new THREE.BoxHelper(cameraBox, 0x0000ff);
  cameraBoundingBox = new THREE.Box3(
    cameraBox.geometry.boundingBox.min,
    cameraBox.geometry.boundingBox.max
  );
  player.add(cameraBoxHelper);
  player.add(cameraBox);
  player.add(camera);
  player.velocity = new THREE.Vector3(0, 0, 0);
  scene.add(player);
  playerMesh = player.children[0];


  camera.position.set(0, 0, 2); // first-player view
  player.position.set(0, 0, 0);
  player.rotation.y = - Math.PI / 2.0;

  VRcontrols = mobile ? new DeviceOrientationControls(camera) : new OrbitControls(camera);

  //LIGHTS
  const light = new THREE.PointLight(0xFFFFFF);
  light.position.set(0, 0, 9);
  light.castShadow = true;
  light.shadow.mapSize.width = 1024;
  light.shadow.mapSize.height = 1024;
  scene.add(light);

  //FLOOR
  const matFloor = new THREE.MeshPhongMaterial();
  const geoFloor = new THREE.BoxGeometry(2000, 1, 2000);
  const mshFloor = new THREE.Mesh(geoFloor, matFloor);

  matFloor.color.set(0x212E39);
  mshFloor.receiveShadow = true;
  mshFloor.position.set(0, - 1, 0);

  scene.add(mshFloor);


  const loader = new ColladaLoader();

  loader.load(`../assets/environment.dae`, collada => {
    collada.scene.traverse(child => {
      child.castShadow = true;
      child.receiveShadow = true;
    });
    scene.add(collada.scene);
    animate();
  });

};

const moveCamera = () => {
  // TODO: find movementX (0= no movement, 1-... = movement)
  //dan -> player.rotateY(rotateAngle * e.movementX * .1);
  const movementX = VRcontrols.object.rotation._y;
  const rotateAngle = Math.PI / 4;
  console.log(VRcontrols.deviceOrientation);

  //player.rotateY(rotateAngle * movementX * .1);
  // notes.forEach(i => {
  //   i.audioCtx.listener.positionX.value = camX + window.innerWidth / 2;
  //   i.audioCtx.listener.positionZ.value = camZ + 300;
  //   i.audioCtx.listener.positionY.value = camY + window.innerHeight / 2;
  // });
  //
  switch (controlData) {
  case `up`:
    camZ -= camSpeed;
    break;
  case `down`:
    camZ += camSpeed;
    break;
  case `left`:
    camX -= camSpeed;
    break;
  case `right`:
    camX += camSpeed;
    break;
  }

  camera.position.set(camX, camY, camZ);
  VRcontrols.update();
};

//CODE BENEATH NEEDS TO BE LESS DIRTY.

const useArrowDown = e => {
  switch (e.key) {
  case `z`:
    moveForward = true;
    break;
  case `s`:
    moveBackward = true;
    break;
  case `q`:
    moveLeft = true;
    break;
  case `d`:
    moveRight = true;
    break;
  }
};

const useArrowUp = e => {
  switch (e.key) {
  case `z`:
    moveForward = false;
    break;
  case `s`:
    moveBackward = false;
    break;
  case `q`:
    moveLeft = false;
    break;
  case `d`:
    moveRight = false;
    break;
  }
};


const animate = () => {

  if (mobile) {
    moveCamera();
  }

  if (moveForward) player.position.z -= .05;
  if (moveBackward) player.position.z += .05;
  if (moveLeft) player.position.x -= .05;
  if (moveRight) player.position.x += .05;

  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;

  renderer.gammaInput = true;
  renderer.gammaOutput = true;

  renderer.setClearColor(0xdddddd, 1);

  renderer.render(scene, camera);

  if (testBoundingBox.intersectsBox(cameraBoundingBox)) {
    console.log(`intersection`);
  }

  requestAnimationFrame(animate);

};


init();

1 个答案:

答案 0 :(得分:3)

您链接的文章包含以下注释:

  

注意:boundingBox属性将Geometry本身作为引用,而不是Mesh。因此,在计算计算框时,将忽略应用于网格的任何变换,例如比例,位置等。

接下来,我使用setFromObject()来设置testBoundingBox的位置,它确实/没有按预期触发交集。这是有趣的代码,以及显示行为的jsfiddle。当然,更改框位置并重新运行以查看交互触发器。

https://jsfiddle.net/87wg5z27/122/

  const testBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const testBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  testBox = new THREE.Mesh(testBoxGeometry, testBoxMaterial);
  testBox.geometry.computeBoundingBox();
  testBoundingBox = new THREE.Box3(
    testBox.geometry.boundingBox.min,
    testBox.geometry.boundingBox.max
  );
  testBox.position.set(5, 0, 5);
  testBoundingBox.setFromObject(testBox); //I added this line
  scene.add(testBox);

  const cameraBoxGeometry = new THREE.BoxGeometry(3, 3, 3);
  const cameraBoxMaterial = new THREE.MeshBasicMaterial({color: 0x00ff00});
  cameraBox = new THREE.Mesh(cameraBoxGeometry, cameraBoxMaterial);
  cameraBox.geometry.computeBoundingBox();
  cameraBoundingBox = new THREE.Box3(
    cameraBox.geometry.boundingBox.min,
    cameraBox.geometry.boundingBox.max
  );
  scene.add(cameraBox);