gpt4 book ai didi

three.js - 如何在three.js中覆盖GLTF Material

转载 作者:行者123 更新时间:2023-12-03 18:44:53 25 4
gpt4 key购买 nike

我正在尝试创建一种动态方式来在 Three.js 中的 gltf 导入模型上显示太阳能数据。目的是将不同的纯色与模型的不同部分相关联,并能够关闭和打开它们。我目前的障碍是更改 gltf 中 Material 的颜色。

我曾尝试使用 ObjLoader 来代替我输入自己的 Material ,但这不起作用:/

这是我目前拥有的js:

        const gltfLoader = new THREE.GLTFLoader();
gltfLoader.load('Building.glb', (gltf) => {
const root = gltf.scene;
scene.add(root);

const box = new THREE.Box3().setFromObject(root);
const boxSize = box.getSize(new THREE.Vector3()).length();
const boxCenter = box.getCenter(new THREE.Vector3());

frameArea(boxSize * 0.5, boxSize, boxCenter, camera);

controls.maxDistance = boxSize * 10;
controls.target.copy(boxCenter);
controls.update();
});


function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
const halfFovY = THREE.Math.degToRad(camera.fov * .5);
const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
const direction = (new THREE.Vector3())
.subVectors(camera.position, boxCenter)
.multiply(new THREE.Vector3(1, 0, 1))
.normalize();

camera.position.copy(direction.multiplyScalar(distance).add(boxCenter));

camera.near = boxSize / 100;
camera.far = boxSize * 100;

camera.updateProjectionMatrix();

// point the camera to look at the center of the box
camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);
}

renderer = new THREE.WebGLRenderer({canvas: myCanvas, antialias: true});
renderer.setClearColor(0x000000);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild( renderer.domElement );



function resizeRendererToDisplaySize(renderer) {
const canvas = renderer.domElement;
const width = canvas.clientWidth;
const height = canvas.clientHeight;
const needResize = canvas.width !== width || canvas.height !== height;
if (needResize) {
renderer.setSize(width, height, false);
}
return needResize;
}

function render() {
if (resizeRendererToDisplaySize(renderer)) {
const canvas = renderer.domElement;
camera.aspect = canvas.clientWidth / canvas.clientHeight;
camera.updateProjectionMatrix();
}
renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);

最佳答案

加载器返回的 gltf.scene 结果是一个 THREE.Scene 实例——一旦你有了它,加载模型所使用的文件格式无关紧要。在这种情况下,您需要遍历该场景并更改其中任何网格的 Material 。 MeshStandardMaterial Mesh 文档可能会有所帮助。

var model = gltf.scene;
var newMaterial = new THREE.MeshStandardMaterial({color: 0xff0000});
model.traverse((o) => {
if (o.isMesh) o.material = newMaterial;
});

如果您需要更改纹理,请注意 GLTFLoader documentation 中的说明。

关于three.js - 如何在three.js中覆盖GLTF Material ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56660584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com