0

So im just starting out learning Javascript, and I'm following the game tutorial in https://www.w3schools.com/graphics/game_obstacles.asp This is the point i've gotten stuck at. If you check out the code in the example, they've added a working obstacle, but the game won't work with the keyboard. (only with buttons added to the site) I want to be able to steer the character with my keyboard, and have a working obstacle, that will stop the game when the two touch.

I would appreciate any help i could get from this. (the code i use is in the example in the link above)

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175

3 Answers3

0

you will need a little bit more than in the shown example.

Here is a reference with an example for key pressed events Link

Short excerpt:

"Clear" JavaScript:

<script type="text/javascript">
  function myKeyPress(e){
    var keynum;

    if(window.event) { // IE                    
      keynum = e.keyCode;
    } else if(e.which){ // Netscape/Firefox/Opera                   
      keynum = e.which;
    }

    alert(String.fromCharCode(keynum));
  }
</script>

<form>
  <input type="text" onkeypress="return myKeyPress(event)" />
</form>

You could also solve it in jquery

JQuery:

$(document).keypress(function(event){
  alert(String.fromCharCode(event.which)); 
});
0

Add this in you code to move the block.

window.addEventListener('keydown', function(event) {
console.log(event);
if(event.keyCode === 38){
    console.log(event);
    myGamePiece.speedY -= 1; 
} else if (event.keyCode === 37){
    myGamePiece.speedX = -1; 
} else if (event.keyCode === 39){
    myGamePiece.speedX = 1; 
} else if (event.keyCode === 40){
    myGamePiece.speedY = 1; 
}

});

Bhavesh Shah
  • 51
  • 1
  • 7
0

Do following changes:

  • Add onkeypress event in body element i.e. <body onkeypress="myFunction(event)" onload="startGame()" >.
  • Define myFunction function as following:
    function myFunction(event)
    {
        switch(event.which || event.keyCode)
        {
        case 117: //Up 'U'
            moveup();
            break;
        case 106: //Down 'J'
            movedown();
            break;
        case 104: //Left 'H'
            moveleft();
            break;
        case 107: //Right 'K'
            moveright();
            break;
        }
    }
    

  • You can get complete working code here. You can copy the complete code and run it locally.

    cse
    • 4,066
    • 2
    • 20
    • 37