如何在 threejs 中独立地将 gltf 模型从定义的场景中独立地移动?
在我的代码中,我更新了一个gltf模型,并尝试使用KeyboardState.js移动它。使用的控件是OrbitControl.js。
键盘状态.js : https://searchcode.com/codesearch/view/69477532/
这是我使用的加载函数:
function loadGLTF(x,y,z,mesh,url){
var loader = new THREE.GLTFLoader();
// model
loader.load(
// resource URL
url,
// called when the resource is loaded
function ( gltf ) {
mesh = gltf.scene;
mesh.position.set(x,y,z);
scene.add(mesh);
},
// called while loading is progressing
function ( xhr ) {
console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
},
// called when loading has errors
function ( error ) {
console.log(error);
console.log( 'An error happened' );
}
);
}
这是我用于键盘输入的更新功能:
function update()
{
keyboard.update();
var moveDistance = 50 * clock.getDelta();
if ( keyboard.down("W") )
mesh.translateY( moveDistance );
if ( keyboard.down("S") )
mesh.translateY( -moveDistance );
if ( keyboard.down("A") ){
console.log("entered in A");
mesh.translateX( -moveDistance );
}
if ( keyboard.down("D") ){
console.log("entered in D");
mesh.translateX( moveDistance );
}
controls.update();
stats.update();
}
但实际上发生的事情是,物体随着所有场景而移动,而不是独立于此。如果我使用相同的代码来移动例如球体,它可以工作。为什么?也许 gltf 文件以隐式方式依赖于场景,而不是简单的 THREE。球体几何不是吗?
您似乎没有正确使用KeyboardState
。这个想法是使用 pressed()
方法来验证是否按下了某个键。您还可以在下面的实时示例中看到,仅平移了glTF
模型,而不是整个场景(因为轴助手位于中心(。
https://jsfiddle.net/kd41ejua/1/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Demo</title>
</head>
<body>
<script src="https://rawcdn.githack.com/mrdoob/three.js/d9f87fb1a2c5db1ea0e2feda9bd42b39b5bedc41/build/three.min.js
"></script>
<script src="https://unpkg.com/three@0.85.0/examples/js/controls/OrbitControls.js"></script>
<script src="https://unpkg.com/three@0.87.1/examples/js/loaders/GLTFLoader.js"></script>
<script>
var scene, camera, renderer;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
scene.background = new THREE.Color(0xefefef);
camera.position.set(5, 5, 5);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var avtar;
var loader = new THREE.GLTFLoader();
loader.load(
"https://rawcdn.githack.com/siouxcitizen/3DModel/a1c2e47550ca20de421f6d779229f66efab07830/yuusha.gltf",
function (gltf) {
avtar = gltf.scene;
scene.add(avtar);
}
);
controls = new THREE.OrbitControls(camera, renderer.domElement);
document.onkeydown = function (e) {
switch (e.keyCode) {
case 37:
avtar.scale.z += 0.1;
break;
case 39:
avtar.scale.z -= 0.1;
break;
}
};
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
}
init();
</script>
</body>
</html>
试试这个例子