I've been experimenting with Three.js and trying to implement movement controls for a rotating cube using the WASD keys. The goal is to move the cube up, down, left, and right, as well as reset it to its original position in the middle of the screen by pressing the space bar. However, I'm facing some difficulties getting the movement functionality to work properly. As a newbie to Three.js, I would really appreciate any help or guidance. Below is the code snippet I've worked on so far:
// initial lines remain consistent
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 );
var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.7 );
scene.add( directionalLight );
// handling movement
document.addEventListener("keydown", onDocumentKeyDown, false);
function onDocumentKeyDown(event) {
var keyCode = event.which;
if (keyCode == 87) { // up
cube.position.y += 1;
} else if (keyCode == 83) { // down
cube.position.y -= 1;
} else if (keyCode == 65) { // left
cube.position.x -= 1;
} else if (keyCode == 68) { // right
cube.position.x += 1;
} else if (keyCode == 32) { // space
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();
The above code represents the JavaScript part of my project. In addition to this file, I have an HTML file that acts as the entry point. Here's how the HTML looks like:
<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>