首页 > 解决方案 > 如何在three.js上通过addEventListener动态更新set.position.x?

问题描述

我有一个带有 addEventListener 的按钮,该按钮带有即将传递的参数。如果我 console.log( referenced button element ) 它控制台就好了。结果,我得到 Vector3 {x: 15, y: 0, z: 0} 控制台上没有显示错误。问题是我无法/尚未确认如何通过 dom / 控制台动态更新更改,以便在出现(按下)带有参数的按钮时设置要重新渲染的立方体 X 位置。我的代码片段:

        var button = document.getElementById("increment");
        button.addEventListener("click", function() { onButtonClick (15)}, false);

        function onButtonClick(customX) {
            var webGLcontext = document.getElementById("WebGL-output");
            webGLcontext = cube.position;
            webGLcontext.set(customX, 0, 0);
            scene.add(webGLcontext);}

       // all the rest stuff of three.js skeleton presented
        }
       // THREE.Object3D.add: object not an instance of THREE.Object3D. Vector3 {x: 15, y: 0, z: 0}

任何帮助或对本主题文章的参考将不胜感激。

标签: three.js

解决方案


你可以用这个选项来处理事情(这只是一个概念,不是最终的解决方案):

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 100);
camera.position.set(0, 8, 13);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

scene.add(new THREE.GridHelper(10, 10));

var box = new THREE.Mesh(new THREE.BoxBufferGeometry(), new THREE.MeshNormalMaterial());
scene.add(box);

[{
    id: 'btnUp',
    move: new THREE.Vector3(0, 0, -1)
  },
  {
    id: 'btnRight',
    move: new THREE.Vector3(1, 0, 0)
  },
  {
    id: 'btnDown',
    move: new THREE.Vector3(0, 0, 1)
  },
  {
    id: 'btnLeft',
    move: new THREE.Vector3(-1, 0, 0)
  }
].forEach(a => {
  let btn = document.getElementById(a.id);
  btn.addEventListener("click", event => {
    box.position.add(a.move); // move the cube in the desired direction
  });
});

renderer.setAnimationLoop(() => { // animation loop
  renderer.render(scene, camera);
});
body {
  overflow: hidden;
  margin: 0;
}

#btnButtons {
  position: absolute;
}

button {
  width: 32px;
  height: 32px;
  margin: 10px;
}
<script src="https://threejs.org/build/three.min.js"></script>
<div id="btnButtons">
  <button id="btnUp">&uarr;</button>
  <button id="btnRight">&rarr;</button>
  <button id="btnDown">&darr;</button>
  <button id="btnLeft">&larr;</button>
</div>

当您移动立方体时,您会看到它的位置是如何自动变化的,因为场景将在动画循环中以特定的帧速率进行渲染。


推荐阅读