解决方案 1:手动过滤 raycast 候选者和结果
看起来没有任何内置字段可以实现您想要的,但您应该能够通过手动过滤要进行光线投射的对象列表来实现类似的行为。以下是您如何做到这一点的想法:
// scene with lots of nested objects
const scene, raycaster;
// ...
// Gather up which objects to try to raycast against based on
// a set of conditions
const raycastList = [];
scene.traverse(c => {
if (c.isMesh && !c.disableRaycast) {
raycastList.push(c);
}
});
// raycast against only the items in the array
const intersections = raycaster.raycastObjects(raycastList);
如果您想基于网格父母disableRaycastfield 进行过滤,那么您可以创建一个自定义遍历函数,让您跟踪父母禁用状态及早停止遍历。
如果您已经提前知道应该或不应该对哪些对象进行光线投射,您可以预先创建该列表并保留它。
编辑
解决方案 2:覆盖并制作自定义 Mesh.raycast() 函数
如果您无权修改光线投射代码,那么您可以创建一个“DeactivateableRaycastMesh”类来实现自定义光线投射方法,并允许您启用或禁用它是否返回光线投射命中。
class DeactivateableRaycastMesh extends THREE.Mesh {
constructor(...args) {
super(...args);
this.raycastEnabled = true;
}
raycast(...args) {
if (!this.raycastEnabled) return;
super.raycast(...args);
}
}
如果您在每个 网格上都需要此功能,而不仅仅是您创建的网格,那么您可以修改THREE.Mesh.prototype 以将上述功能添加到所有网格。但是不建议这样做。
const originalRaycast = THREE.Mesh.prototype.raycast;
THREE.Mesh.prototype.raycast = function(...args) {
if (!this.raycastEnabled) return;
originalRaycast.call(this, ...args);
}