4

I know its possible but I cant seem to figure it out. In its basic form I have a canvas circle moving 5 pixels every key event however this seems to be rather slow at firing and really jumpy, plus it stalls when changing key or changing from rapid key press to holding down.

So can someone enlighten me of a way ofwhich this could work without it stuttering?

Thanks.

2
  • You probably want to attach your code for more responses:) Commented Mar 31, 2011 at 18:30
  • 90.197.69.193/html5/game.html Is what I have so far, its just me testing. Ignore the random missile particle that fecks up just focus on the red ball :P Commented Mar 31, 2011 at 18:33

2 Answers 2

10

What you want to do is set variables on keydown and keyup to true or false that you check every tick. Something like this:

var tickRate = 30,
    keyDown = {},
    keyMap = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };

$('body').keydown(function(e){ keyDown[keyMap[e.which]] = true;  });
$('body').keyup(function(e){   keyDown[keyMap[e.which]] = false; });

var tick = function() {
  if        (keyDown['up']) {
    // up code
  } else if (keyDown['down']) {
    // down code
  } else if (keyDown['left']) {
    // left code
  } else if (keyDown['right']) {
    // right code
  }

  // other code

  setTimeout(tick, tickRate);
};

tick();
Sign up to request clarification or add additional context in comments.

2 Comments

Is it okay if I use that code to try stuff out? (Plus it doesnt bind on body weirdly which is why I used *) Looks good, I didnt even think of doing it like that. Ill put the tick inside the loop I already have going though. Thanks alot :)
It's only ok for you to use this code if you pay it forward by helping others with their coding problems when you can. :) P.S. I just noticed I used jQuery when you didn't ask for it. Consider my answer to be partially pseudo-code, but you get the idea.
3

The main problem you have here is that you are at the mercy of the "key repeat" functionality of the Operating System. Usually if you hold a key down, a keyPress event will be generated once, then (after a delay) on a repeat. But if you want to control this delay/repeat, then that's not good enough.

Instead I'd have your own polling function, set to run every few milliseconds, checking whether each key you're interested in is down or up. Then you know that, for every poll whilst the key is down, some event can be fired regardless of the OS's settings.

You can then apply your own algorithms and multipliers to smooth the movement out.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.