Hi I’m making a small game. It involves a vacuum cleaner. I want the vacuum only to move up and down when the space key is pressed.
My problem is the vacuum is moving up and down when any key is pressed, and when more than one key is pressed at the same time the vacuum gets buried somewhere on the page.
window.onload = docReady();
var vacuum = document.getElementById('vacuum');
var spaceKey = 32;
var fired = false;
function setPosition(element, x, y){
element.style.left = x + 'px';
element.style.top = y + 'px';
}
function spaceReleased() {
window.onkeyup = function() {
vacuum.style.top = parseInt(vacuum.style.top) + 100 + 'px';
fired = false;
}
}
function moveVacuum(evt) {
if(fired === false) {
fired = true;
vacuum.style.top = parseInt(vacuum.style.top) - 100 + 'px';
}
if(evt.keyCode !== spaceKey) {
//do nothing
}
console.log(evt.keyCode)
}
window.addEventListener('keydown', moveVacuum);
window.addEventListener('keyup', spaceReleased);
function docReady(){
var vacuum = document.getElementById('vacuum');
setPosition(vacuum, 550, 415);
}