You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React-Three-Fiber中创建拉伸成型的不规则3D多边形

自定义切角木方实现方案

你代码无法渲染拉伸模型的核心问题有两个:

  1. R3F的<mesh>组件会自动创建Mesh实例,你提前在JSX外new出来的Mesh对象不会被挂载到场景树中,自然不会渲染
  2. 尺寸和相机视口不匹配:你用的正交相机zoom为25,可视范围很小,你定义的形状尺寸+缩放比例过大,直接超出了可视区域

基础实现(2D形状拉伸)

你需要的两端切角木方完全可以用2D形状拉伸的方案实现,符合R3F规范的写法如下:

import { ExtrudeGeometry, Shape, MeshLambertMaterial } from 'three'
import { useTrimesh } from '@react-three/rapier'

const Cut2x4Wood = () => {
  // 定义木方截面的2D形状,可自行调整参数匹配切角角度
  const woodSection = new Shape()
  const sectionWidth = 2 // 2x4木方截面宽度
  const sectionHeight = 4 // 2x4木方截面高度
  const cutSize = 0.5 // 切角大小,调整这个值可以改变切角角度

  woodSection.moveTo(0, 0)
  woodSection.lineTo(cutSize, sectionHeight)
  woodSection.lineTo(sectionWidth - cutSize, sectionHeight)
  woodSection.lineTo(sectionWidth, 0)
  woodSection.lineTo(0, 0)

  // 拉伸参数
  const extrudeConfig = {
    amount: 10, // 木方的长度
    bevelEnabled: false
  }

  // 缓存几何和材质避免重复创建
  const geometry = new ExtrudeGeometry(woodSection, extrudeConfig)
  const material = new MeshLambertMaterial({ color: '#8B4513' })

  // 加物理碰撞,不规则形状用useTrimesh传入几何的顶点和索引即可
  const [phyRef] = useTrimesh(() => ({
    type: 'Static',
    position: [0, 0, 0],
    args: [geometry.attributes.position.array, geometry.index.array]
  }))

  return <mesh ref={phyRef} geometry={geometry} material={material} />
}

简化方案

如果切角是常规的45度斜切,也可以用两个Box拼接成需要的形状,性能更高,物理碰撞直接用useBox分别设置即可,开发效率更高。

原有三角形拉伸demo修复

你之前写的三角形测试代码只要改两个地方就能正常显示:

  • 把提前创建的trussBoard1Extruded直接传给<mesh>的geometry属性,material同理,不需要提前创建Mesh实例
  • 把moveSize改成0.2左右,去掉scale属性或者设为1,适配当前相机的可视范围

内容的提问来源于stack exchange,提问作者NealWalters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:24:03