在 THREE.Js 的场景中添加同一导入模型的多个副本

发布于 2025-01-20 18:53:11 字数 619 浏览 3 评论 0 原文

我已经将3D模型导入了我一直在研究的三个项目中,我想在现场添加几份副本。这是我一直使用的代码来复制它:

let ball = new THREE.Mesh();
loader.load( './ball.gltf', function ( gltf ) {
    gltf.scene.traverse(function(model) { //for gltf shadows!
        if (model.isMesh) {
          model.castShadow = true;
          model.material = sphereMaterial;
        }
    });
    ball = gltf.scene;
    scene.add( ball );
}, undefined, function ( error ) {
    console.error( error );
} );

const ball2 = ball.clone()
ball2.position.set(0.5, 0.5, 0.5)
scene.add(ball2)

但是,从 loader.load()呼叫中仅显示一个“球”中的一个“球”。有人碰巧知道我应该做些什么以成功复制模型吗?

I've imported a 3D model into a THREE.Js project I've been working on, and I want to add several copies of them to the scene. Here's the code I've been using to duplicate it:

let ball = new THREE.Mesh();
loader.load( './ball.gltf', function ( gltf ) {
    gltf.scene.traverse(function(model) { //for gltf shadows!
        if (model.isMesh) {
          model.castShadow = true;
          model.material = sphereMaterial;
        }
    });
    ball = gltf.scene;
    scene.add( ball );
}, undefined, function ( error ) {
    console.error( error );
} );

const ball2 = ball.clone()
ball2.position.set(0.5, 0.5, 0.5)
scene.add(ball2)

However, only one of the "balls" show up in the scene from the loader.load() call. Does anyone happen to know what I should do differently to successfully duplicate the model?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔戏命师 2025-01-27 18:53:11

您的 onload() handler(函数(GLTF){...} )是异步的,并且clones ball ball 的代码() const ball2 = ball.clone())在使用GLTF数据初始化 Ball 之前执行。因此,在当时 ball.clone()执行, ball 只是您在加载GLTF之前创建的空的网格,而该空 >网格是克隆的。

我怀疑您在某个时候是在不确定的 clone 上遇到的控制台错误,这就是为什么您将行添加到空的 ball 中添加到空的网格,这是不必要的。

有几种方法可以处理此操作,但最简单的是将克隆 ball 的代码移动到 onload handler( ie )之后,之后代码> scene.add(ball))。

概念证明在这里

Your onLoad() handler (function ( gltf ) {...}) is asynchronous, and the code that clones ball (const ball2 = ball.clone()) is executing before ball is initialized with the GLTF data. So at the time ball.clone() executes, ball is simply the empty Mesh you created before loading the GLTF, and that empty Mesh is what gets cloned.

I suspect you were, at some point, getting a console error relating to reading clone on undefined, and that's why you added the line to initialize ball to an empty Mesh, which is unnecessary.

There are a few ways to handle this, but the simplest is to move the code that clones ball into the onLoad handler (i.e., after scene.add( ball )).

Proof of concept here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文