Understanding Vertical Movement Method in "Eloquent Jav

Understanding Vertical Movement Method in "Eloquent JavaScript"

本文关键字:quot Eloquent Jav in Vertical Movement Method Understanding      更新时间:2023-09-26

最近我一直在从Eloquent JavaScript学习JavaScript;目前我在第15章"项目:平台游戏"。我一直在浏览代码,并捕捉到了所有内容,但我遇到了一个方法,当作者解决沿垂直轴的移动时:

var gravity = 30;
var jumpSpeed = 17;
Player.prototype.moveY = function ( step, level, keys ) {
    this.speed.y += step * gravity;
    var motion = new Vector( 0, this.speed.y * step );
    var newPos = this.pos.plus( motion );
    var obstacle = level.obstacleAt( newPos, this.size );
    if ( obstacle ) {
        level.playerTouched( obstacle );
        if ( keys.up && this.speed.y > 0 )
            this.speed.y = -jumpSpeed;
        else
           this.speed.y = 0;
    } else {
        this.pos = newPos;
    }
};

我不确定gravitythis.speed.y在这种情况下是如何工作的,我希望你能帮助我更好地理解它。

我的问题:

特别是,在第五行this.speed.y += step * gravity上,speed.y之前没有在程序中声明过,因此我希望该程序会出现错误,如果发生其他事情,有人可以向我解释吗?

另外,我不明白重力是如何在这里实现的(为什么step * gravity表示初始速度,然后再乘以步长——步长是动画中的时间)?

我希望我能正确地解释自己,并非常感谢你的建议。

如果您查看该章的其余代码,您会注意到this.speed初始化为:

this.speed = new Vector(0, 0);

Vector在代码中定义为:

function Vector(x, y) {
  this.x = x; this.y = y;
}

因此,第一次运行this.speed.y += step * gravity时,this.speed.y已经初始化为0。

(我在找到了完整的代码http://eloquentjavascript.net/code/chapter/15_game.js)