从sketchfab.com下载3D模型并将其导入到Three.js场景中后,它们大多数时候都没有居中,并且尺寸很大。
是否有一种方法可以使用脚本或软件(在Linux上运行)自动对gltf模型进行定中心和缩放,或者在Three.js中即时进行,并使用OrbitControls使相机在对象周围移动
答案 0 :(得分:2)
是的。该代码获取一个节点并找到其大小和中心点,然后对其进行重新缩放,以使最大范围为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);
答案 1 :(得分:1)
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
答案 2 :(得分:0)
其他建议的解决方案对我而言效果不佳。 但是,我在下面的几种模型上测试了简单的方法,将其加载到场景中,效果很好。
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);
}
);
答案 3 :(得分:0)
我像这样在 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 />