gpt4 book ai didi

javascript - 我的 for 循环正在创建项目符号对象但没有将它们渲染到屏幕上

转载 作者:行者123 更新时间:2023-11-30 19:21:15 25 4
gpt4 key购买 nike

我正在创建一个太空入侵者游戏,坦克和外星人渲染到屏幕,但子弹不会渲染。网络控制台也不是显示任何错误。

子弹创建对象并将它们存储在数组中。那是工作当我使用 console.log() 时,它不会在屏幕上显示矩形。

Web 控制台也没有显示任何错误。

    //this is in file helpers.js

//create the bullets

function Bullet(x, y, vely, w, h, color){
this.x = x;
this.y = y;
this.vely = vely;
this.w = w;
this.h = h;
this.color = color;
};

Bullet.prototype.update = function() {
this.y += this.vely;
};

SScreen.prototype.drawBullet = function(bullet){
this.ctx.fillStyle = this.color;
this.ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
}

//this is in file main.js

//this is in my update function

if (input.isPressed(32)) {
bullets.push(new Bullet(tank.x, tank.y, -8, 2, 6), "#FFF")
};

//this is in my render function

scr.ctx.save();
for (var i = 0, len = bullets.length; len < 0; i++) {
scr.drawBullet([i]);
}
scr.ctx.restore();

结果是当按下空格键时,水箱附近会出现一个矩形但什么也没出现

最佳答案

我在这里发现了一些错误,希望这对您有所帮助。

<强>1。 Bullet 对象的颜色属性:

if (input.isPressed(32)) {
bullets.push(new Bullet(tank.x, tank.y, -8, 2, 6), "#FFF")
};

您没有通过 color进入new Bullet ,所以颜色属性变成了undefined .

请尝试:

if (input.isPressed(32)) {
bullets.push(new Bullet(tank.x, tank.y, -8, 2, 6,"#FFF"))
};

但是我注意到你不需要 draw 函数中的 bullet.color,所以你可以忽略这部分。

<强>2。 for 循环的条件和传递给 drawBullet 的参数:

for (var i = 0, len = bullets.length; len < 0; i++) {
scr.drawBullet([i]);
}

一个。条件是len < 0 ,它导致这个 for 循环永远不会执行。

项目符号对象未传递到 drawBullet

请尝试:

for (var i = 0, len = bullets.length; i < len; i++) {
scr.drawBullet(bullets[i]);
}

<强>3。 Bullet 对象的 w & h :

SScreen.prototype.drawBullet = function(bullet){
this.ctx.fillStyle = this.color;
this.ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
}

bullet.width , bullet.height不存在。

请尝试:

SScreen.prototype.drawBullet = function(bullet){
this.ctx.fillStyle = this.color;
this.ctx.fillRect(bullet.x, bullet.y, bullet.w, bullet.h);
}

关于javascript - 我的 for 循环正在创建项目符号对象但没有将它们渲染到屏幕上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57447607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com