three.js - 如何在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}
任何帮助或对本主题文章的参考将不胜感激。
解决方案
你可以用这个选项来处理事情(这只是一个概念,不是最终的解决方案):
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">↑</button>
<button id="btnRight">→</button>
<button id="btnDown">↓</button>
<button id="btnLeft">←</button>
</div>
当您移动立方体时,您会看到它的位置是如何自动变化的,因为场景将在动画循环中以特定的帧速率进行渲染。
推荐阅读
- tags - 在 Shopify 中的订单信息中添加一个标识符,该标识符将传递到我们的第 3 方履行中心
- javascript - 原始表达被打破
- python - 在python中逐行读取文件并在for循环python中使用
- asp.net-core - 使用 Web 部署将 ASP.NET Core MVC 发布到 IIS 失败
- pandas - 使用循环根据列的值绘制子图
- javascript - 多个按钮,每个按钮都有唯一的计数器
- c++ - 在 Excel 中挂钩 ReadFile 函数
- reactjs - React hook useState 不会从第一次更新数组
- angular - 如何在有/没有订阅的情况下以角度发出帖子请求?
- azure - Azure DevOps Pipeline:带有通知的代码扫描器