1

I have a problem using the raycaster:

When I create an object at the center (0, 0, 0) the raycaster can hit it. But whatever reason for if I move the object to (0, 300, 0) or somewhere else the raycaster will stop hitting the object.

All Directions were 100% setup correct. I tested raycasting the moved object by my self step by step using the Three.js functions and it worked.

It seems that the raycaster.IntersectsObject(objects) is not applying the matrixWorld correctly to the Bounding Sphere.

Any idea why?

I know there is a similar Post on this topic, but the solution did not work out for me:

Three JS - Strange raycast behaviour when objects are moved

The boundingsphere has the correct values.

1 Answers1

1

You have ensure that the world matrix of your mesh is up to date. You can easily fix this by calling mesh.updateMatrixWorld();.

var camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
camera.position.set( 400, 200, -300 );

var scene = new THREE.Scene();

var geometry = new THREE.SphereBufferGeometry(100, 100, 100);
var material = new THREE.MeshBasicMaterial({
  color: 0xaa5555
});

var mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, 300, 0);
mesh.updateMatrixWorld(); // FIX
scene.add(mesh);

camera.lookAt( mesh.position );

var raycaster = new THREE.Raycaster();
var ray = raycaster.ray;
ray.origin.copy( camera.position );
ray.direction.subVectors( mesh.position, camera.position ).normalize();

var intersections = raycaster.intersectObjects(scene.children);
console.log( intersections ); 

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

renderer.render( scene, camera );
body {
  margin: 0;
}
canvas {
  display: block;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.119/build/three.js"></script>
Mugen87
  • 28,829
  • 4
  • 27
  • 50