Three.js中自动居中和调整GLTF模型大小

11

从sketchfab.com下载3D模型并将它们导入到Three.js场景中后,它们大多数情况下不会居中,大小也非常大。

是否有一种脚本或软件(在Linux上工作),可以自动居中和缩放gltf模型,或者在Three.js中实时进行操作并使用OrbitControls移动摄像机围绕物体。

4个回答

13

是的。这段代码获取节点的尺寸和中心点,然后重新调整比例,使最大范围为1,并且居中于0,0,0,并在y轴上方离地面一定距离。

    var mroot = yourScene;
    var bbox = new THREE.Box3().setFromObject(mroot);
    var cent = bbox.getCenter(new THREE.Vector3());
    var size = bbox.getSize(new THREE.Vector3());

    //Rescale the object to normalized space
    var maxAxis = Math.max(size.x, size.y, size.z);
    mroot.scale.multiplyScalar(1.0 / maxAxis);
    bbox.setFromObject(mroot);
    bbox.getCenter(cent);
    bbox.getSize(size);
    //Reposition to 0,halfY,0
    mroot.position.copy(cent).multiplyScalar(-1);
    mroot.position.y-= (size.y * 0.5);

你的场景是一个场景对象的路径还是一个实际的对象?你能提供一些关于你解决方案的更多上下文吗? - Casivio
你的场景将是你想获取其边界的场景/对象。在你的GLTF加载示例中,你可以使用let mroot = gltf.scene。希望对你有所帮助! - manthrax

7
var loader = new THREE.GLTFLoader();
loader.load( 'models/yourmodel.gltf', 
function ( gltf ) {
    gltf.scene.traverse( function ( child ) {
        if ( child.isMesh ) {
            child.geometry.center(); // center here
        }
    });
    gltf.scene.scale.set(10,10,10) // scale here
    scene.add( gltf.scene );
}, (xhr) => xhr, ( err ) => console.error( e ));

要移动物体,请使用controls.target()控件 https://threejs.org/docs/#examples/controls/OrbitControls.target


3
我不确定这如何解决我的问题,物体仍然偏移。 而且你的提议中缩放参数不是自动的。 - b26

3

我在 React 中进行了如下调整!

import React, { useState, useRef, useEffect } from "react";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
const Earth = () => {
const [model, setModel] = useState();
useEffect(() => {
    new GLTFLoader().load("scene.gltf", (model) => {
      model.scene.scale.set(0.03, 0.03, 0.03);
      setModel(model);
    });
  });
  return model ? <primitive object={model.scene} /> : null;
};

只需调用 <Earth />


2

其他提出的解决方案对我来说效果不佳。然而,我在多个要加载到场景中的模型上测试了下面的简单方法,效果很好。

const loader = new GLTFLoader();
loader.load("assets/model_path/scene.gltf",
      (gltf) => {
        gltf.scene.scale.multiplyScalar(1 / 100); // adjust scalar factor to match your scene scale
        gltf.scene.position.x = 20; // once rescaled, position the model where needed
        gltf.scene.position.z = -20;

        scene.add(gltf.scene);
        render();
      },
      (err) => {
        console.error(err);
      }
    );

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