I'm currently stuck while trying to develop a game in Javascript. My challenge lies in detecting keypresses and constantly checking if they are being held down to move the character. Below is the code I have been using:
var THREE;
var keys;
var update;
var scene = new THREE.Scene();
var renderer = new THREE.WebGLRenderer();
var player_fov = 45;
var player_aspect = window.innerWidth / window.innerHeight;
var player_near = 0.1;
var player_far = 10000;
var player_camera = new THREE.PerspectiveCamera(player_fov, player_aspect, player_near, player_far);
var player_material = new THREE.MeshNormalMaterial({color: 0xd0bd4b});
var player_geometry = new THREE.BoxGeometry(1,1,1,1);
var player = new THREE.Mesh(player_geometry, player_material);
function INIT()
{
scene.add(player);
player_camera.position.z = 5;
window.addEventListener('keydown', function (e) {
keys.keys = (keys.keys || []);
keys.keys[e.keyCode] = true;
});
window.addEventListener('keyup', function (e){
keys.keys[e.keyCode] = false;
});
requestAnimationFrame(INIT);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.render(scene, player_camera);
if(keys.keys && keys.keys[87]) //w
{
player.position.y += 1;
}
if(keys.keys && keys.keys[65]) //a
{
player.position.x -= 1;
}
if(keys.keys && keys.keys[83]) //s
{
player.position.y -= 1;
}
if(keys.keys && keys.keys[68]) //d
{
player.position.x += 1;
}
}
The movement isn't working properly despite pressing different keys. It should be an easy error to identify for experienced programmers. Is there something wrong with my understanding of event listeners or requestAnimationFrame? If so, please provide guidance on how to rectify it. Thank you.