从旋转的网格投射多条光线



我正在尝试从旋转网格拍摄多条光线。射线向多个方向射向(以圆上的点为目标,除以射线数)。

为了调试的目的,我为每条射线添加了ArrowHelpers。这个想法是,如果箭头击中什么东西,应该变成红色,如果没有变成白色。它们也根据与相交物体的距离改变长度,当它们不相交时,它们的长度保持在射线的最大长度(远)。

到目前为止,我所拥有的是每条射线都保持检查旋转网格的相同(我认为)前进方向。我相信我需要找到公式来计算基于对象当前旋转的新归一化向量。我尝试过很多不同的东西,比如object3D.localToGlobalVector3.applyQuaternion等……然而,我的数学能力不及格

代码沙箱地址:https://codesandbox.io/s/raycast-issue-bch05b

Raycasting代码:

import {  RefObject } from "react";
import * as THREE from "three";
import React from "react";
import { useFrame, useThree } from "@react-three/fiber";
export type RayCastResult = {
hit: boolean;
angle: number;
direction: THREE.Vector3;
distance: number;
};
export const useRaycasts = ({
count = 4,
near = 1,
far = 10,
obj
}: {
count?: number;
near?: number;
far?: number;
obj: RefObject<THREE.Mesh>;
}): { rays: RayCastResult[] } => {
const rays = React.useMemo(() => {
const rays: RayCastResult[] = [];
let angle = 0;
const step = (2 * Math.PI) / count;
for (let i = 0; i < count; i++) {
rays.push({
hit: false,
angle: angle,
direction: new THREE.Vector3(
Math.cos(angle),
0,
Math.sin(angle)
).normalize(),
distance: 10
});
angle += step;
}
return rays;
}, [count]);
const pos = React.useMemo(() => new THREE.Vector3(), []);
const dir = React.useMemo(() => new THREE.Vector3(), []);
const { scene, raycaster } = useThree();
useFrame(() => {
if (!obj.current) return;
obj.current.getWorldDirection(dir);
obj.current.getWorldPosition(pos);
rays.forEach((direction, i) => {
if (!obj.current) return;
raycaster.set(
pos,
dir
.applyAxisAngle(rays[0].direction, obj.current?.rotation.y)
.normalize()
//dir.applyAxisAngle(rays[i].direction, rays[i].angle),
//dir.applyAxisAngle(rays[i].direction, Math.PI / 2)
//dir.applyQuaternion(obj.current.quaternion).add(rays[i].direction)
);
raycaster.near = near;
raycaster.far = far;
const intersects = raycaster.intersectObjects(scene.children);
// ONLY check first object
if (intersects.length) {
rays[i].hit = true;
rays[i].distance = intersects[0].distance;
} else {
rays[i].hit = false;
rays[i].distance = raycaster.far;
}
});
});
return { rays };
};

好吧,回答我自己的问题,希望这可能会在将来有人使用…

似乎我的方法是对的,我实际上在另一个stackoverflow问题中找到了答案,解决方案在问题中!

解决方案是使用3。Matrix4类,复制旋转网格的旋转。然后,该旋转矩阵应应用于给定光线的方向。

在夏天的:

// construct a Matrix4 class (do it once to save resources)
const matrix = useMemo(() => new THREE.Matrix4(), []);
// Later inside the loop:
// get the object's current position
obj.current.getWorldPosition(pos);
// copy the objects rotation matrix to our matrix
matrix.extractRotation(obj.current.matrix);
// apply the rotation to the ray direction
raycaster.set(pos, dir.copy(rays[i].direction).applyMatrix4(matrix));

签出更新的沙箱

最新更新