使用 Three.js,当我使用 position.set() 定位对象时,THREE.Raycaster 似乎不知道对象的新设置位置。如果我将对象留在 0,0,0 处,则网格会正确相交。
function init(){
var targets = [];
var object;
// More scene initializing code...
// creating a cube object and placing 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 created and added to the scene
}
我有一个角色控制器,我可以用跟随的相机四处移动,因此我将角色 (obj) 和目标插入到函数 testRay() 中进行测试;
function testRay(obj,targets,distance){
// code to keep the ray pointing out in front of the character at all times
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);
}
}
然后每次 requestAnimationFrame(main) 调用,我 testRay() 插入角色控制器和目标以查看它是否相交。
function main(){
// some other code
testRay(character,targets,30)
window.requestAnimationFrame(main);
}
好的,所以问题不是让它相交,这很好用。在创建期间使用 position.set() 后,它与对象的新位置相交。我注意到我可以简单地通过相交来移动对象,这似乎也移动了相交坐标。将对象添加到场景后移动会更好吗?有区别吗?