3
\$\begingroup\$

How to create good timer for HTML5 Canvas games? I am using RequestAnimationFrame( http://paulirish.com/2011/requestanimationframe-for-smart-animating/ )

But object's move too fast.

Something like my code is:

http://pastebin.com/bSHCTMmq

But if I press UP_ARROW player don't move one pixel, but move 5, 8, or 10 or more or less pixels. How to do if I press UP_ARROW player move 1 pixel?

Thanks for help.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ don't move the user on keydown/up/press check for the keypress during the frame animation and move him/her then. that way you will only move 1pt max per frame. I still don't think this is the best way to do it. or try this dailycoding.com/Posts/… \$\endgroup\$
    – rlemon
    Commented May 30, 2012 at 13:17
  • 2
    \$\begingroup\$ @rlemon you should make an answer out of that comment. \$\endgroup\$
    – bummzack
    Commented May 30, 2012 at 14:26

3 Answers 3

2
\$\begingroup\$

The player is moving 1 pixel, but because you are constantly polling for input, you get the 'isdown' response every frame. So in the space of 1 second, you have moved 60 pixels, assuming frame rate holds and you held down the key for the whole second.

What you would need to do is only perform the movement code, as soon as the key was pressed, that way the player will need to release the key to be able to move again. Something like this should do the trick.

Player.prototype.init = function() {
    this.pressed = {};  // List of pressed keys
};

Player.prototype.update = function() {
    if ( !keyboard.up()) {
        delete this.pressed[ 'up'];  // No longer pressed, so remove
    }
    if ( keyboard.up() && !this.pressed[ 'up']) {
        this.pressed[ 'up'] = true; // Set to pressed so the event doesn't fire again
        this.y --;
    }
};

I suggest altering your input class so that it would be handled for you, but the code is pretty much identical.

\$\endgroup\$
0
\$\begingroup\$

The problem here is you're moving it according to the frame-rate and not frame-rate independent.

If you read this article you'll understand how to implement delta time steps. Now, with this in mind you'll have what you need to ACTUALLY move the player correctly. If you want the player to move 32 pixels per SECOND, you would do something like....

   if( keyboard.up() ) {
     this.y -= 32 * gameTime;
}

This will move the player 32 pixels every second, regardless of the frame-rate in the browser. This is ideal as you are now guaranteed 32 pixels on every browser, machine and configuration available. If you don't do this, you are subject to frame-rate fluctuation.

\$\endgroup\$
0
\$\begingroup\$

I made an answer on a related matter that might interest you :

How can I detect and compensate for system related lag?

( maybe i could copy-paste it here for reader convenience... )

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .