0

我一直在关注如何在 HTML5 中制作简单游戏的本教程,我遇到了一个我无法理解的参数的有趣用法......这里作者使用单个参数 I 创建了一个名为 Bullet 的构造函数,但是看他如何使用我。这是怎么回事?我不明白:

function Bullet(I) {
    I.active = true;

    I.xVelocity = 0;
    I.yVelocity = -I.speed;
    I.width = 3;
    I.height = 3;
    I.color = "#000";

    I.inBounds = function() {
        return I.x >= 0 && I.x <= CANVAS_WIDTH &&
        I.y >= 0 && I.y <= CANVAS_HEIGHT;
    };

    I.draw = function() {
        canvas.fillStyle = this.color;
        canvas.fillRect(this.x, this.y, this.width, this.height);
    };

    I.update = function() {
        I.x += I.xVelocity;
        I.y += I.yVelocity;
    };

    return I;
}
4

1 回答 1

2

根据该教程,Bullet它不是构造函数,只是一个接受现有对象、增加(附加)属性并返回对象的函数。然后它将返回的对象(带有附加属性)放入playerBullets数组中。

playerBullets.push(Bullet({  //the Bullet call, passing an object
    speed: 5,
    x: bulletPosition.x,
    y: bulletPosition.y
}))

从返回的对象Bullet将如下所示:

{
    //the passed object
    x:...,
    y:...,
    speed:...,
    //the added properties
    xVelocity:...,
    yVelocity:...,
    ...,
    update:function(){...}
}
于 2012-04-29T00:13:23.123 回答