在场景中可见的情况下,找不到针对网格的光线投射

时间:2016-08-26 06:45:49

标签: three.js

我遇到了一个奇怪的光线投射问题。我的场景包括一个有几个组件的房间,你可以在那个房间内移动。当部件移动时,我正在测量到墙壁的距离,一个看不见的屋顶和地板。问题是作为ShapeGeometry的屋顶是可见的,它应位于墙的顶部,但在光线投射时不会被击中。

这是我为隐形屋顶创建网格的地方

const roofShape = new THREE.Shape();
roofShape.moveTo(roofPoints[0].x, roofPoints[0].y);
for (let i = 1; i < roofPoints.length; i++) {
    roofShape.lineTo(roofPoints[i].x, roofPoints[i].y);
}
roofShape.lineTo(roofPoints[0].x, roofPoints[0].y);

const geometry = new THREE.ShapeGeometry(roofShape);

const material = new THREE.MeshBasicMaterial({color: 0x000000, side: THREE.DoubleSide});
material.opacity = 0;
material.transparent = true;
const mesh = new THREE.Mesh(geometry, material);
mesh.position.x = 0;
mesh.position.y = 0;
mesh.position.z = room._height;
mesh.name = "ROOF";
mesh.userData = <Object3DUserData> {
    id: IntersectType.INVISIBLE_ROOF,
    intersectType: IntersectType.INVISIBLE_ROOF,
};

调用光线投射的功能。在这种情况下,方向矢量是(0,0,1)。 surface参数是一个只包含上面创建的网格的数组。

function getDistanceToSurface(componentPosition: THREE.Vector3, surfaces: THREE.Object3D[], direction: THREE.Vector3): number {
    const rayCaster = new THREE.Raycaster(componentPosition, direction.normalize());
    const intersections = rayCaster.intersectObjects(surfaces);

    if (!intersections || !intersections.length) {
        return 0;
    }

    const val = intersections[0].distance;

    return val;
}

通过将z方向改为-1,我发现raycaster在z = 0处找到了屋顶。似乎几何图形仍处于z = 0的位置。

然后我尝试翻译几何形状

geometry.translate(0, 0, room._height);

现在,raycaster发现它在我预期的位置。但在视觉上它是z位置的两倍(网格不透明度= 1)。将网格位置z设置为0使其明显正确,并且光线投射仍然有效。

我一直在研究光线投射的例子,但找不到ShapeGeometry需要的任何地方。

我做错了吗?我错过了什么吗?我是否必须设置几何体的z位置,定位网格是不够的?

1 个答案:

答案 0 :(得分:0)

如@radio在comment中暗示的那样,解决方案如How to update vertices geometry after rotate or move object

中所述
mesh.position.z = room._height;
mesh.updateMatrix();
mesh.geometry.applyMatrix(mesh.matrix);
mesh.matrix.identity();
相关问题