Home > Blockchain >  how can i enter keyboard events
how can i enter keyboard events

Time:06-24

I was working on this project of UFO, Now I want to move this UFO by using arrow keys Up, Down ,left , right. I am unable to do so

function Up() {
    if ((pos) >=10) {
      pos -= 5;
      document.querySelector
      document.querySelector(`img`).style.top = pos   "px";
    }
  }

  function Down() {
    if ((pos) <=870) {
      pos  = 5;
      document.querySelector(`img`).style.top = pos   "px";
    }
  }
  function Left() {
    if ((posLeft) >= 10) {
      posLeft -= 5;
      document.querySelector(`img`).style.left = posLeft   "px";
    }
  }
  function Right() {
    if ((posLeft) <= 1880) {
      posLeft  = 5;
      document.querySelector(`img`).style.left = posLeft   "px";
    }
  }

CodePudding user response:

To add keyboard event handlers you can do the following, after your function declarations:

document.addEventListener("keydown", (e) => {
  switch(e.code){
    case "ArrowUp":
      Up();
      break;
    case "ArrowLeft":
      Left();
      break;
    case "ArrowRight":
      Right();
      break;
    case "ArrowDown":
      Down();
      break;
  }
})

many tutorials or articles online will point you towards KeyboardEvent.keyCode, but it has been deprecated and shouldn't hence be used.

CodePudding user response:

To prevent the annoying delay when initially holding down a key, you could add the current key to an array, and remove it when you're finished with it. Here is how you could do it...

// Array of currently pressed keys
const keys = [];

// Add pressed key to array if it's not already pressed
document.addEventListener("keydown", (e) => {
    if (!keys.includes(e.key)) {
    keys.push(e.key);
  }
});

// Remove released key if it's in the array
document.addEventListener("keyup", (e) => {
  if (keys.includes(e.key)) {
    keys.splice(keys.indexOf(e.key), 1);
  }
});

// Move UFO based on current pressed keys every 100ms
setInterval(() => {   
  if (keys.includes("w")) {
    console.log("Move up!");
  }
  if (keys.includes("s")) {
    console.log("Move down!");
  }
  if (keys.includes("a")) {
    console.log("Move left!");
  }
  if (keys.includes("d")) {
    console.log("Move right!");
  }
}, 100);
  • Related