bufferGeometry setFromPoints with react-three-fiber

str*_*tss 3 javascript three.js reactjs react-three-fiber

考虑toLinePath功能:

const toLinePath = (arrayOfPoints, color = 0x000000) => {
  const path = new THREE.Path();
  const firstPoint = arrayOfPoints[0];

  path.moveTo(firstPoint.x, firstPoint.y, firstPoint.z);
  arrayOfPoints.forEach(point => path.lineTo(point.x, point.y, point.z));
  path.closePath();

  const points = path.getPoints();
  const geometry = new THREE.BufferGeometry().setFromPoints(points);
  const material = new THREE.LineBasicMaterial({ color });
  const line = new THREE.Line(geometry, material);
  return line;
};
Run Code Online (Sandbox Code Playgroud)

我想使用react-three-fiber并尝试这样的方法重新创建它:

import React from 'react'
import * as THREE from 'three'
import ReactDOM from 'react-dom'
import { Canvas } from 'react-three-fiber'

function LinePath(props) {
  const vertices = React.useMemo(() => {
    const path = new THREE.Path()
    const firstPoint = props.vertices[0]

    path.moveTo(firstPoint.x, firstPoint.y, firstPoint.z)
    props.vertices.forEach(point => path.lineTo(point.x, point.y, point.z))
    path.closePath()

    return path.getPoints()
  }, [props.vertices])

  return (
    <line>
      <bufferGeometry attach="geometry" setFromPoints={vertices} />
      <lineBasicMaterial attach="material" color="black" />
    </line>
  )
}


ReactDOM.render(
  <Canvas>
    <LinePath vertices={[new THREE.Vector3(0, 0, 0), new THREE.Vector3(2, 2, 0), new THREE.Vector3(-2, 2, 0)]} />
  </Canvas>,
  document.getElementById('root')
)
Run Code Online (Sandbox Code Playgroud)

但是根本没有输出/错误。我想我完全误解了react-three-fibers API。我在这里做错了什么?谢谢,这是沙盒

str*_*tss 8

所以我真的想通了。我正在寻找的是useUpdate钩子,它允许我们调用任何给定的ref. 所以这就是需要做的事情:

import { Canvas, useUpdate } from 'react-three-fiber'

function LinePath(props) {
  const vertices = ...

  const ref = useUpdate(geometry => {
    geometry.setFromPoints(vertices)
  }, [])

  return (
    <line>
      <bufferGeometry attach="geometry" ref={ref} />
      ...
    </line>
  )
}
Run Code Online (Sandbox Code Playgroud)


小智 5

对于未来的 Google 员工,useUpdate 已在此处删除:

https://github.com/pmndrs/react- Three-Fiber/pull/ 996 。

请改用 useLayoutEffect

 const ref = React.useRef<BufferGeometry>(null!);
  useLayoutEffect(() => {
    if (ref.current) {
      ref.current.setFromPoints(points);
    }
  }, []);

  return (
    <line>
      <bufferGeometry attach='geometry' ref={ref} />
      <lineBasicMaterial color={0xff0000} />
    </line> 
  );
Run Code Online (Sandbox Code Playgroud)