When using Three.js, I encountered an issue where the THREE.Raycaster does not recognize an object's new position set using position.set(). If the object is left at the default position of 0,0,0, the mesh is properly intersected.
function initialize(){
var targets = [];
var object;
// Additional scene initialization code...
// Creating a cube object and positioning it at (-10,0,-10)
var objectGeometry = new THREE.CubeGeometry(2,2,2);
var objectMaterial = new THREE.PhongMeshMaterial({color: 0xEEEEEE });
object = new THREE.Mesh(objectGeometry, objectMaterial);
object.position.set(-10, 0, -10);
scene.add(object);
targets.push(object);
// More objects are created and added to the scene
}
I have a character controller that can be moved around with a camera following it. To test, I connect the character (obj) and the targets in a function called testRay();
function testRay(obj,targets,distance){
// Code to ensure the ray is always pointing out in front of the character
var endRayX = (Math.cos((270*(Math.PI/180))-obj.rotation.y)*distance + obj.position.x);
var endRayZ = (Math.sin((270*(Math.PI/180))-obj.rotation.y)*distance + obj.position.z);
var vector = new THREE.Vector3(endRayX,obj.position.y,endRayZ);
var raycaster = new THREE.Raycaster(obj.positon,vector);
intersects = raycaster.intersectObjects(targets);
if(intersects.length>0){
console.log("intersects.length: "+ intersects.length);
console.log("intersects.distance: "+ intersects[0].distance);
console.log("intersects.face: "+ intersects[0].face);
console.log("intersects.point: " + intersects[0].point);
console.log("intersects.object: " + intersects[0].object);
}
}
During each requestAnimationFrame(main) call, I call testRay() with the character controller and targets to check for intersections.
function main(){
// Some other code
testRay(character,targets,30)
window.requestAnimationFrame(main);
}
The issue lies in getting the ray to intersect the object at its new position set with position.set() during creation. I observed that simply intersecting the objects can move them around, which also shifts the intersection coordinates. Should I move the object after adding it to the scene? Does it make a difference?