-2

I am making an animation/Game.

It already has a ifkeypressed and you even enter the key.

But when I play the animation no matter what key I press it continues.

I was wondering if there was a way to run something when the D key is pressed. In this example it would run play();.

I will also need w, a, and s.

My code:

function keyReleased(key) {
    event
}

P.S. i made sure and i went through w/ my original code and even though i have the key set as "d" even when i press (for example when i went through i pressed space) a key it still runs it.

jwpfox
  • 5,124
  • 11
  • 45
  • 42
James
  • 17
  • 4

2 Answers2

0

You need to add an event listener to track the key event. In the below example I used keyup as this will run once the key has been released.

In the callback function of the event listener you will be given an event object and from this object you can check something called a keyCode (or in older browsers which). Each key on the keyboard has a mapped number to it so you can trace back to whether a D, W, A, or S was passed for instance and call different methods based on that.

I've written some generic object oriented code below to show how this could be achieved. See how the event is passed from addEventListener callback to keyPressed, and keyPressed runs the logic for moveRight if the code matches 68.

function GameName() {
  // ... constructor stuff ...

  // add keypressed method on keyup
  document.addEventListener('keyup', function(event) {
     this.keyPressed(event);  
  }.bind(this));
}

GameName.prototype.keyPressed = function(event) {
  // browser compatibility check for event and event code
  var e = event || window.event,
      code = e.which || e.keyCode;

  // If user pressed 'D' key (google for javascript key codes)
  if (code === 68) {
    this.moveRight();
  }
}

GameName.prototype.moveRight = function(event) {
   // user moves right
}
Joe Methven
  • 518
  • 4
  • 15
0

You can assign a function to a specific key in a few ways:

function play() {
  alert("I'm playing!");
}

document.addEventListener("keydown", checkKeyPressed, false);

function checkKeyPressed(e) {
  if (e.keyCode == 68) {
    play();
  }
}

or

function play() {
  alert("I'm playing!");
}

document.onkeydown = function(e){
  e = e || window.event;
  var key = e.which || e.keyCode;
  if(key == 68){
    play();
  }
}

or with JQuery

function play() {
  alert("I'm playing!");
}

$(document).keydown(function(e) {
  if (e.keyCode == 68) {
    play();
  }
});

The key codes for "w", "a", and "s" are 87, 65, and 83 respectively. Here is a list of all the codes: https://stackoverflow.com/a/45534377/3080392

user3080392
  • 1,194
  • 5
  • 18
  • 35