使用threejs的Raycasting会抛出错误

时间:2018-02-13 15:21:22

标签: three.js raycasting

尝试使用threejs进行光线投射,但我在控制台中收到此错误。

Uncaught TypeError: a.raycast is not a function
乐不完整 http://jsfiddle.net/hw9rcLL8/147/

有什么想法吗?

// Simple three.js example
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var mesh, renderer, scene, camera, controls;

window.addEventListener('click', mouseClick);

init();
animate();

function init() {

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

  // scene
  scene = new THREE.Scene();

  // camera
  camera = new THREE.PerspectiveCamera(40, window.innerWidth / window.innerHeight, 1, 10000);
  camera.position.set(20, 20, 20);

  // controls
  controls = new THREE.OrbitControls(camera);

  // ambient
  scene.add(new THREE.AmbientLight(0x222222));

  // light
  var light = new THREE.DirectionalLight(0xffffff, 1);
  light.position.set(20, 20, 0);
  scene.add(light);

  // axes
  scene.add(new THREE.AxisHelper(20));

  // geometry
  var geometry = new THREE.SphereGeometry(5, 12, 8);

  // material
  var material = new THREE.MeshPhongMaterial({
    color: 0x00ffff,
    shading: THREE.FlatShading,
    transparent: true,
    opacity: 0.7,
  });

  // mesh
  mesh = new THREE.Mesh(geometry, material);
  scene.add(mesh);

}

function animate() {

  requestAnimationFrame(animate);

  //controls.update();

  renderer.render(scene, camera);

}

function mouseClick(e) {
  console.log("click detected");
  mouse.x = (e.clientX / renderer.domElement.width) * 2 - 1;
  mouse.y = -(e.clientY / renderer.domElement.height) * 2 + 1;
  raycaster.setFromCamera(mouse, camera);

  var intersects = raycaster.intersectObject(scene.children);
}
body {
  background-color: #000;
  margin: 0px;
  overflow: hidden;
}
<script src="https://rawgit.com/mrdoob/three.js/dev/build/three.min.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js"></script>

1 个答案:

答案 0 :(得分:2)

你错过了s:D - 它应该是

raycaster.intersectObjects(scene.children);

您撰写intersectObject的地方。这是针对单个对象而不是数组:

raycaster.intersectObject(mesh);