在 @react-three/fiber 中使用 lookAt

7
我正在尝试学习如何在react中使用three js。为此,我正在使用@react-three/fiber@react-three/drei
我使用chriscourses的这个项目来学习three js,并希望用它来学习如何在react中使用threejs。
下面的代码应该显示从给定坐标中发出的方框,但当前它们都倾斜向一个方向。使用lookat应该解决问题,但我不知道如何在@react-three/fiber / @react-three/drei中使用lookat
import React, { FC, useRef } from 'react';
import { Box as NativeBox } from '@react-three/drei'
import { Vector3 } from 'three';
import { useFrame } from '@react-three/fiber';


type Props = {
  country: any,
}
const lookAtCubePosition = new Vector3(0, 0, 0)
const Box: FC<Props> = (props) => {
  const mesh = useRef()
  
  const { country } = props;
  const scale = country.population / 1000000000
  const lat = country.latlng[0]
  const lng = country.latlng[1]
  const zScale = 0.8 * scale

  const latitude = (lat / 180) * Math.PI
  const longitude = (lng / 180) * Math.PI
  const radius = 5

  const x = radius * Math.cos(latitude) * Math.sin(longitude)
  const y = radius * Math.sin(latitude)
  const z = radius * Math.cos(latitude) * Math.cos(longitude)

  console.log('box');

  const lookAtFunc = (lookAt: Vector3) => {
    lookAt.x = 0;
    lookAt.y = 0;
    lookAt.z = 0;
  }

  useFrame((state) => {
    state.camera.lookAt(lookAtCubePosition)
  })


  return <NativeBox
    args={[
      Math.max(0.1, 0.2 * scale),
      Math.max(0.1, 0.2 * scale),
      Math.max(zScale, 0.4 * Math.random())
    ]}
    position={[
      x, y, z
    ]}
    lookAt={lookAtFunc}
    ref={mesh}
  >
    <meshBasicMaterial
      attach="material"
      color="#3BF7FF"
      opacity={0.6}
      transparent={true}
    />
  </NativeBox>;
};

export default Box;
2个回答

4
如果您正在使用OrbitControls,必须设置OrbitControls的“目标”而不是相机的lookAt,因为相机的lookAt被OrbitControls覆盖。

0

我认为(文档对此并不太具体),我们不应该将lookAt设置为属性,而是应该将其用作函数。我们可以使用useThree钩子访问活动相机。

在作为Canvas子级挂载的组件中执行以下操作:

import { useThree } from "@react-three/fiber";

// Takes a lookAt position and adjusts the camera accordingly
const SetupComponent = (
  { lookAtPosition }: { lookAtPosition: { x: number, y: number, z: number } }
) => {
  // "Hook into" camera and set the lookAt position
  const { camera } = useThree();
  camera.lookAt(lookAtPosition.x, lookAtPosition.y, lookAtPosition.z);
  
  // Return an empty fragment
  return <></>;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接