Exemplo keypress (setas)

by Cthulhu

HTML

<main>
  <p>tecla: <span>00</span></p>
  <div id="carro"></div>
  <audio id="apita">
    <source src="http://static1.grsites.com/archive/sounds/vehicle/vehicle040.mp3">
  </audio>
</main>

CSS

main {
  background: #24B41D url('http://www.java-online.ch/gamegrid/bb/sprites/roadCircle.png') no-repeat;
  background-position: -20px -50px;
  height: 100%;
  position: fixed;
  width: 100%;
  z-index: 0;
}

p {
  color: white;
  font-size: 24px;
  left: 240px;
  position: absolute;
  top: 210px;
}

#carro {
  background: url('https://openclipart.org/image/800px/svg_to_png/61201/simple-travel-car-top-view.png');
  background-size: 100px auto;
  height: 50px;
  position: absolute;
  left: 100px;
  top: 440px;
  width: 100px;
  z-index: 1;
}

JavaScript

$("body").keydown(function(e) {
  //Qual a tecla?
  $('span').text(e.keyCode);

  if (e.keyCode == 37) { // Esquerda  
    $("#carro").css({
      'left': '-=5px',
      'transform': 'rotate(180deg)'
    });
  } else if (e.keyCode == 39) { // Direita     
    $("div").css({
      'left': '+=5px',
      'transform': 'rotate(0deg)'
    });
  } else if (e.keyCode == 38) { // Cima     
    $("div").css({
      'top': '-=5px',
      'transform': 'rotate(270deg)'
    });
  } else if (e.keyCode == 40) { // Baixo     
    $("div").css({
      'top': '+=5px',
      'transform': 'rotate(90deg)'
    });
  }
});

$("body").keydown(function(f) {
  $('span').text(f.keyCode);
  if (f.keyCode == 72) { // H     
    document.getElementById('apita').play();
  }
})