Question

I'm working on a little game using HTML5 canvas and javascript. Now what I am trying to do is to make an image move from left to right and when pressing a key it changes image to make it look more like it is moving.

Now I got that working but I'm kind of stuck. The code is that when you press the left key he changes the player.image to player.imgLeft and when releasing change it back to the normal image.

The pressing works but the releasing doesn't.. What am I doing wrong?

Here is in short the code

 // Things to do when keys are down
 function onKeyDown(event)
 {
if (event.keyCode >= 37 && event.keyCode<=39)
    event.preventDefault(); // prevent arrow keys from scrolling the page

switch (event.keyCode) {
 case 37: player.vx = -1; player.image = player.imgLeft; break; // left key
 case 38: player.vy = -1; break; // up key
 case 39: player.vx = 1; player.image = player.imgRight; break; // right key
 }  
 }


 // Things to do when keys are up
 function onKeyUp(event)
 {
switch (event.keyCode) {
    case 37: case 39: player.vx = 0; player.imgLeft = player.image; break; // left or right key released
    case 38: player.vy = 0; break; // up or down key released
  }
 }
Was it helpful?

Solution

Modify like this if you have your original image in player.original.. Onkeyup event you should use like this ...

function onKeyUp(event)
 {
switch (event.keyCode) {
    case 37: case 39: player.vx = 0; player.image = player.original; break; // left or right key released
    case 38: player.vy = 0; break; // up or down key released
  }
 }

OTHER TIPS

When you press the key, you do

player.image = player.imgLeft

and when you release, you do

player.imgLeft = player.image;

which does nothing, as both variables hold the same value. You need a third variable to store the original player.image value.

Remember:

If you are using onkeydown="return onKeyDown(event)" you need onkeyup="return onKeyUp(event)".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top