bufferGeometry setFromPoints 与 react-three-fiber

Posted

技术标签:

【中文标题】bufferGeometry setFromPoints 与 react-three-fiber【英文标题】:bufferGeometry setFromPoints with react-three-fiber 【发布时间】:2020-01-20 09:11:51 【问题描述】:

考虑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;
;

我想使用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')
)

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

【问题讨论】:

【参考方案1】:

所以我真的想通了。我正在寻找的是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>
  )

【讨论】:

由于某种原因不适合我。不进入useUpdate回调函数 没有一些代码什么也说不出来。创建沙盒

以上是关于bufferGeometry setFromPoints 与 react-three-fiber的主要内容,如果未能解决你的问题,请参考以下文章

三维空间中绘制点线面UV贴图,万能的BufferGeometry(three.js实战4)

#yyds干货盘点#BufferGeometry的setDrawRange的使用

如何快速更新大的BufferGeometry?

Three.js 中 BufferGeometry 的渲染顺序

Three.js索引BufferGeometry与InstancedBufferGeometry

Three.js - 大型网格的 BinaryLoader 与 BufferGeometry?