I’m creating a simple game with a character that can jump, move right, and move left.
I’m having trouble with the jump function, which uses a setInterval.
Here is the function:
jumpUp: function (speed) {
setInterval(function () {
this.yPos += 10;
this.playerElement.css("top", '-=' + 10);
alert("dude, im not moving....so stop trying"); //for some reson, this line works and other dont.
}, 100);
}
I should add that the code works without the setInterval. I really don’t have any idea why it’s not working when I add the setInterval.
My questions:
- What is stopping this code from running?
- Is
setIntervala good way to make a character look like it jumping and landing? Or should i use different method?
EDIT 1:
The problem is your use of
this. When the function you pass tosetIntervalis called,thiswill be the global object (windowin browsers). You need to preserve thethisvalue from when you callsetInterval. One way of doing this is to store the value ofthisinto a variable, which will then be closed over by the anonymous function (which is a closure):EDIT:
To answer your second question, a better approach to animating a sprite (like your character) is to store the character’s velocity, and then have a single game loop that will calculate the next position of the sprite based on that information. A very simple example would look like: