The problem is using this . When you call the setInterval function, this will be a global object ( window in browsers). You need to save this value when you call setInterval . One way to do this is to store the this value in a variable, which will then be closed by an anonymous function (which is closure):
jumpUp: function (speed) { var self = this; setInterval(function () { self.yPos += 10; self.playerElement.css("top", '-=' + 10); }, 100); }
EDIT:
To answer the second question, the best approach to animating a sprite (for example, your character) is to maintain the speed of the character, and then have one game loop that will calculate the next position of the sprite based on this information. A very simple example:
// Somewhere else in the code: function tick() { // move player by player.velocity.x and player.velocity.y // code to decelerate player gradually, stop player when they hit a wall/floor, etc... // A very simple example: if (player.velocity.y > 0) { player.velocity.y -= 1 } // call next tick() (setTimeout, or preferably requestAnimationFrame) } // In the player code: velocity: {x: 0, y: 0}, jumpUp: function () { this.velocity.y -= 10; }, moveRight: function () { this.velocity.x += 10; }
source share