three初始化加载模,居中且大小固定
three初始化加载模,居中且大小固定
方案一:
动态居中模型位置,缩放到一定大小
modelCenter(object) { let scale = this.modelSize(object); object.scale.set(scale, scale, scale); let box = new THREE.Box3().setFromObject(object); let mdlen = box.max.x - box.min.x; let mdwid = box.max.z - box.min.z; let mdhei = box.max.y - box.min.y; let x1 = box.min.x + mdlen / 2; let y1 = box.min.y + mdhei / 2; let z1 = box.min.z + mdwid / 2; object.position.set(-x1, -y1, -z1); }, modelSize(object) { let box = new THREE.Box3().setFromObject(object); let mdlen = box.max.x - box.min.x; let mdwid = box.max.z - box.min.z; let mdhei = box.max.y - box.min.y; let max = Math.max(mdlen, mdwid, mdhei); let scale = 110 / max; return scale; },
方案二:
控制相机位置,剧中模型,缩放到一定大小
changeCamera(){
let box3 = new THREE.Box3()
let obj=this.scene.getObjectByName('person');
box3.expandByObject(obj)
let size = new THREE.Vector3()
box3.getSize(size)
let center = new THREE.Vector3()
box3.getCenter(center)
let max = this.maxSize(size)
this.camera.position.copy(center.clone().addScalar(max))
this.camera.lookAt(obj)
this.camera.near = max * 0.1
this.camera.far = max * 300
// 用四元素进行旋转
const quaternionY = new THREE.Quaternion()
quaternionY.setFromAxisAngle(new THREE.Vector3(0,1,0), -Math.PI/5)
this.camera.position.applyQuaternion(quaternionY)
const quaternionX = new THREE.Quaternion()
quaternionX.setFromAxisAngle(new THREE.Vector3(1,0,0), Math.PI/6)
this.camera.position.applyQuaternion(quaternionX)
this.camera.updateProjectionMatrix()
this.orbitControls.target.copy(center)
this.orbitControls.update()
},
maxSize(vec3) {
let max
if (vec3.x > vec3.y) {
max = vec3.x
} else {
max = vec3.y
}
if (max > vec3.z) {
} else {
max = vec3.z
}
return max
},
在加载模型的时候,调用这个函数
loadFBX() {
let manager = new LoadingManager();
manager.addHandler(/\.tga$/i, new TGALoader());
const fbxLoader = new FBXLoader(manager);
this.modelPath = this.getModelPath();
fbxLoader.load(this.modelPath, (object) => {
object.name = "person";
this.fbxData = object;
this.initFbxData = JSON.parse(JSON.stringify(object));
this.changeTexture(object);
this.scene.add(object);
this.modelTexure();
this.changeCamera()
});
},
如有疑问,可加qq群学习讨论:910316886