简体   繁体   中英

how can i enter keyboard events

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";
    }
  }

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.

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 = [];

// Attempt to add pressed key
document.addEventListener("keydown", (e) => {
  if (!keys.includes(e.key)) { // If key isn't already pressed
    keys.push(e.key); // Add key to array
  }
});

// Attempt to remove pressed key
document.addEventListener("keyup", (e) => {
  if (keys.includes(e.key)) { // If key is already pressed
    keys.splice(keys.indexOf(e.key), 1); // Remove key from array
  }
});

// Move UFO based on current pressed keys every 100ms
setInterval(() => {   
  if (keys.includes("w")) { // If the 'keys' array contains 'w', then move up
    // Move up!
    Up();
  }
  if (keys.includes("s")) {
    // Move down!
    Down();
  }
  if (keys.includes("a")) {
    // Move left!
    Left();
  }
  if (keys.includes("d")) {
    // Move right!
    Right();
  }
}, 100);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM