以下代码是我到目前为止使用三个j来尝试使用WASD键向上,向下,向左和向右移动或翻译旋转立方体对象,并重置为原始位置(屏幕中间)带空格键。我是三个j的新手,我无法弄清楚如何使机芯运转。任何帮助将不胜感激。这就是我到目前为止所做的:
// first 5 lines are a template and should be pretty much the same always
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// end template here
var geom = new THREE.BoxGeometry(10, 10, 10);
var mat = new THREE.MeshBasicMaterial({color: "red"});
var cube = new THREE.Mesh(geom, mat);
scene.add(cube);
camera.position.x = 2;
camera.position.y = 1;
camera.position.z = 20;
var light = new THREE.AmbientLight( 0x404040 ); // soft white light
scene.add( light );
// White directional light at 70% intensity shining from the top.
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
scene.add( directionalLight );
// movement
document.addEventListener("keydown", onDocumentKeyDown, false);
function onDocumentKeyDown(event) {
var keyCode = event.which;
// up
if (keyCode == 87) {
cube.position.y += 1;
// down
} else if (keyCode == 83) {
cube.position.y -= 1;
// left
} else if (keyCode == 65) {
cube.position.x -= 1;
// right
} else if (keyCode == 68) {
cube.position.x += 1;
// space
} else if (keyCode == 32) {
cube.position.x = 0.0;
cube.position.y = 0.0;
}
render();
};
var render = function() {
requestAnimationFrame(render);
cube.rotation.x += 0.03;
cube.rotation.y += 0.02;
cube.rotation.z += 0.01;
renderer.render(scene, camera);
};
render();
这只是javascript文件。我还有一个单独的HTML文件来启动。这是HTML:
<html><head><title>WebGL with three.js</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head><body>
<script src="three.js"></script>
<script src="Learn_Cube3.js"></script>
</body></html>
答案 0 :(得分:5)
这个怎么样? -
// movement - please calibrate these values
var xSpeed = 0.0001;
var ySpeed = 0.0001;
document.addEventListener("keydown", onDocumentKeyDown, false);
function onDocumentKeyDown(event) {
var keyCode = event.which;
if (keyCode == 87) {
cube.position.y += ySpeed;
} else if (keyCode == 83) {
cube.position.y -= ySpeed;
} else if (keyCode == 65) {
cube.position.x -= xSpeed;
} else if (keyCode == 68) {
cube.position.x += xSpeed;
} else if (keyCode == 32) {
cube.position.set(0, 0, 0);
}
};
要移动对象,您必须更改对象的位置。另外,根据需要校准xSpeed
和ySpeed
。
答案 1 :(得分:0)
在按键事件中重新调用您的渲染方法:
function onDocumentKeyDown(event) {
...
render();
};
问题在于您正在更新值,但是当事情发生变化时,ThreeJS不会自动重新渲染视图,您必须告诉它重新渲染。
编辑:在渲染方法中,您只修改旋转属性,因此立方体只会旋转。你还需要告诉ThreeJS立方体的新位置。
我不认为你的解决方案是&#34; xSpeed&#34;和&#34; ySpeed&#34;如果有效,你需要实际添加/减去position.x和position.y值。