I am currently working on a script where I need to increment a variable by 5 each time the up key is pressed. The issue I am facing is that the variable keeps increasing continuously from a single keypress, whereas I want it to increase in steps of 5 (e.g., 5, 10, 15, 20...).
Below is the code I have written so far. Any help in identifying my mistake would be greatly appreciated.
var projectileHeight = 5;
function setHeight()
{
projectileHeight += 5;
};
if (keyCode == 38)
{
setHeight();
console.log(projectileHeight);
};
The code related to the keycode for the up key is placed within a rendering function used with requestAnimationFrame(). Moving this outside the function did not resolve the issue.
Javascript is being used alongside THREE.js & Physi.js.
Additional code:
var render = function() {
requestAnimationFrame(render);
scene.simulate();
let keyFlag = false;
document.addEventListener("keydown", (e) => {
if(e.code == 'ArrowUp'){
if (!keyFlag) {
keyFlag = true;
projectileHeight += 5;
console.log(projectileHeight);
}
}
});
document.addEventListener("keydown", (e) => {
if(e.code == 'ArrowDown'){
if (!keyFlag) {
keyFlag = true;
projectileHeight -= 5;
console.log(projectileHeight);
}
}
});
document.addEventListener("keyup", (e) => {
if(e.code == 'ArrowUp' || e.code == 'ArrowDown'){
if (keyFlag){
console.log("stopped");
keyFlag = false;
}
}
});
renderer.autoClear = false;
renderer.clear();
renderer.render(backgroundScene, backgroundCamera);
renderer.render(scene, camera);
};
This function includes keypress detection within the render function and initiates animation frames and game physics.
The function is called immediately after declaration.
Thank you for your assistance.