在函数中访问'this'变量传递给setInterval/setTimeout

sam*_*amy 4 javascript jquery setinterval

我正在制作一个简单的游戏,其角色可以跳跃,向右移动,向左移动.

我在使用跳转功能时遇到问题setInterval.

这是功能:

 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);
}
Run Code Online (Sandbox Code Playgroud)

我应该补充一点,代码在没有的情况下工作setInterval.当我添加时,我真的不知道它为什么不起作用setInterval.

我的问题:

  1. 什么阻止此代码运行?
  2. setInterval一个让角色看起来像跳跃和着陆的好方法吗?或者我应该使用不同的方法?

编辑1:

小提琴

Geo*_*rge 6

问题是你的使用this.调用传递给的函数时setInterval,this将是全局对象(window在浏览器中).您需要保留this调用时的值setInterval.这样做的一种方法是将值存储this到变量中,然后由匿名函数(这是一个闭包)将其关闭:

 jumpUp: function (speed) {
        var self = this;
        setInterval(function () {
            self.yPos += 10;
            self.playerElement.css("top", '-=' + 10);
        }, 100);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

要回答你的第二个问题,一个更好的动画精灵(如你的角色)的方法是存储角色的速度,然后有一个游戏循环,它将根据该信息计算精灵的下一个位置.一个非常简单的例子如下:

// 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;
}
Run Code Online (Sandbox Code Playgroud)