检查数组中的变量

checking variable within array

本文关键字:变量 数组 检查      更新时间:2023-09-26

第一次在这里发帖,第一次用Javascript创建游戏。

我正在尝试在游戏中的两个对象(子弹和敌人(之间创建碰撞,但现在,只是尝试仅用子弹到达屏幕顶部时发生一些事情。

当我按 E 时,会发生这种情况:

if (69 in keysDown && timer == 0) //E
     {  
    var newbullet = Object.create(bullet);
    newbullet.posx = ship.playerx;
    newbullet.posy = ship.playery;
    projectiles.push(newbullet);
    ship.shoot = true;
     }

然后,项目符号向上移动,如其更新功能中所述。

我在我的游戏循环中不断运行这个函数,它检查冲突,看起来像这样:

function Collision()
{
        for (i = 0; i <= projectiles.length; i++)
        {
            if (bullet.posy < 0 )
            {
                ctx.fillText("HIT" , 160, 340);
                ship.health -= 1;
            }
        }
}

但它不起作用。我想用"projectiles[i].posy"代替"bullet.posy",但最终说projectiles[i]是未定义的。

射弹是一个全局阵列。

var projectiles=[];

这是项目符号:

var bullet = 
    {
        posx:0,
        posy:0,
        speed: 10,
        power: 2,
        draw: function()
        {
            ctx.fillStyle = "rgb(200,100,0)";
            ctx.beginPath();
            ctx.rect(((this.posx - 5)), (this.posy - 30), 10, 25);
            ctx.closePath();
            ctx.fill();
        },
        setup: function(ax, ay)
        {
            this.posx = ax;
            this.posy = ay;
        },
        update: function()
        {
            this.posy -= this.speed;
        }
    };

有什么帮助或建议吗?

这是链接,如果你想尝试一下E 拍摄。

谢谢。

第一部分似乎很清楚:调用一个名为 newbullet 的新项目符号对象,键的值由 ship.playerxship.playery 设置.posx.posy。 然后将newbullet存储在projectiles数组中。

其余的就不太清楚了。正如你所看到的,Collision() 中 for 循环的 if 条件似乎引用了new bullet()构造函数的.posy而不是刚刚创建的对象的.posy(newbullet(。 您还需要迭代 for 循环projectiles.length - 1次,因为数组是零索引的:因此请使用 < 运算符,而不是 for 循环中的<=运算符。

假设ship.playery分配了一个数字值,也许尝试在"射弹"数组通过 Collision() 的 for 循环时为它中的每个项目分配一个变量......

function Collision() {
    var projLength = projectiles.length; // slight optimisation to for-loop
    for (i = 0; i < projLength; i++) {
        var thisBullet = projectiles[i]; // reassign variable each iteration
        if (thisBullet.posy < 0 ) {
            ctx.fillText("HIT" , 160, 340);
            ship.health -= 1;
        }
    }
}

编辑:根据更新的问题

由于您拥有用于存储子弹的projectiles数组,您可以轻松地将bullet文字对象转换为构造器,并根据需要/允许任意数量进行构建。然后,您的代码将遵循我第一段中的描述,看起来像......

var projectiles = [];
var Bullet = function(x, y) {
    this.posx: x,
    this posy: y,
    speed: 10,
    power: 2,
    draw: function() {
        ctx.fillStyle = "rgb(200,100,0)";
        ctx.beginPath();
        ctx.rect(((this.posx - 5)), (this.posy - 30), 10, 25);
        ctx.closePath();
        ctx.fill();
    },
    setup: function(ax, ay) {
        this.posx = ax;
        this.posy = ay;
    },
    update: function() {
        this.posy -= this.speed;
    }
};
/* --- */
if (69 in keysDown && timer == 0) { // E  
    var bullet = new Bullet(ship.playerx, ship.playery);
    projectiles.push(bullet);
    ship.shoot = true;
}
/* --- */
function Collision() {
    // as above ....
}

。这也意味着您不必等待子弹到达y < 0就可以创建另一个子弹。 速射耶!!