Enhance text rendering in Scene component by adding a reference for dynamic camera alignment and refactoring mesh creation for improved clarity.

This commit is contained in:
2025-03-24 15:42:05 +08:00
parent 500460d071
commit 76a530b293

View File

@ -97,21 +97,27 @@ const Scene = () => {
const helper = <cameraHelper args={[camera]} /> const helper = <cameraHelper args={[camera]} />
// @ts-expect-error 16 elements // @ts-expect-error 16 elements
camera.applyMatrix4(new THREE.Matrix4(...extrinsic)) camera.applyMatrix4(new THREE.Matrix4(...extrinsic))
const textRef = useRef<THREE.Mesh>(null)
const { camera: viewCamera } = useThree()
useFrame(() => {
if (textRef.current) {
textRef.current.lookAt(viewCamera.position)
}
})
let text: JSX.Element | null = null let text: JSX.Element | null = null
if (name) { if (name) {
// https://github.com/pmndrs/react-three-fiber/discussions/832
const geo = new THREE_ADDONS.TextGeometry(name ?? "", { font, size: textSize ?? 0.1, depth: 0.001 }) const geo = new THREE_ADDONS.TextGeometry(name ?? "", { font, size: textSize ?? 0.1, depth: 0.001 })
// Extract camera position from extrinsic matrix
const matrix = new THREE.Matrix4() const matrix = new THREE.Matrix4()
// @ts-expect-error 16 elements // @ts-expect-error 16 elements
matrix.set(...extrinsic) matrix.set(...extrinsic)
const position = new THREE.Vector3() const position = new THREE.Vector3()
position.setFromMatrixPosition(matrix) position.setFromMatrixPosition(matrix)
// Create text without applying camera matrix transformation
text = ( text = (
<mesh position={position}> <mesh ref={textRef} position={position}>
<primitive object={geo} /> <primitive object={geo} />
<meshStandardMaterial color="black" /> <meshStandardMaterial color="black" />
</mesh> </mesh>