0

Here is my small attempt at working with Game Loop. Here is the Demo. (keep clicking in gray area to start it).

The issue is that the game animations get choppy after clicking for a while, and reach to a point where it's like a stop motion thing, and after that I need to kill the browser tab.

Surely there is something I'm missing here. May be something like a delay that needs to be inserted when the game is idle.
Here is the code that i've been working on:
HTML

<div class="container">
    <div class="player"></div>
</div>

JavaScript

var player = {
    height: 0,
    width: 0,
    image: "",
    score: 0,
    highestScore: 0
};
var newColor=null;

/*Game loop starts here*/
var gameLoop = function () {
    $(".container").on("click", function () {
        $(".player").stop().animate({
            bottom: "+=100px"
        }, 300, function () {
            $(".player").animate({
                bottom: "0"
            }, 800);
        });
    });
/* some more calls to updating player properties etc etc will come here*/
};
/*Game loop ends here*/

/*Run the Game Loop*/
setInterval(gameLoop, 16);


To state my question:
How do I prevent the lag that I'm experiencing as the game progresses?
md1hunox
  • 3,815
  • 10
  • 45
  • 67
  • It is hard to say where the lag is coming from and if it is due to just the loop. That said I do notice you keep doing $('.player') selector twice per loop. It seems you could gain some efficiency by selecting player only 1 time. – sgmeyer Feb 26 '14 at 16:26
  • 1
    Hello, I think you'll achieve what you want to do more easily with this link: http://apps.apolinariopassos.com.br/flappygenerator/en/ – Xavier Delamotte Feb 26 '14 at 16:27
  • @XavierDelamotte What I'm doing isn't a Flappy bird clone. Its supposed to be some guy with jet pack. Also my attempt to learn building Games using this Game Loop. – md1hunox Feb 26 '14 at 17:47

1 Answers1

4

The lag is coming from you assigning a new click handler every 16 ms.

Extract the following code outside of the gameLoop function:

$(".container").on("click", function () {
    $(".player").stop().animate({
        bottom: "+=100px"
    }, 300, function () {
        $(".player").animate({
            bottom: "0"
        }, 800);
    });
});

You haven't posted the rest of your code, but make sure that in the gameLoop you update the state of the game only and don't re-create the mechanisms that keep the game running.

Tibos
  • 27,507
  • 4
  • 50
  • 64