【发布时间】:2019-04-09 00:54:13
【问题描述】:
我不知道该怎么说,因为我实际上并不知道究竟是什么导致了这个错误。我正在尝试制作一个简单的小行星仿冒品。
当玩家射击时,使用array.push(...) 创建一个新对象(子弹)。一旦此项目符号超出画布(超出范围),就会使用 array.splice(...); 删除它
问题在于子弹以不可预测的方式移动。我不知道如何措辞所以这里是完整的代码(工作,包括 html/css):https://pastebin.com/tKiSnDzX 按住空格键几秒钟(拍摄),您会清楚地看到问题。您也可以使用 A/D 转弯和 W 前进。
这就是我认为正在发生的事情。只要屏幕上(数组中)只有一个项目符号,代码就可以正常运行。这意味着要么不正确的元素被删除,要么进入对象构造函数的值在途中的某个地方搞砸了。
Exhibit A(bullet 构造函数及其方法):
function Bullet(x,y,rot,vel) {
this.x = x;
this.y = y;
this.rot = rot;
this.vel = (vel+5);
this.move = function() {
this.x += this.vel*Math.cos(this.rot-Math.PI/2);
this.y += this.vel*Math.sin(this.rot-Math.PI/2);
}
this.draw = function() {
engine.circle(this.x, this.y, 4, "black");
var c = engine.canvas.getContext('2d');
c.translate(this.x, this.y);
c.rotate(this.rot);
c.beginPath();
c.strokeStyle="#00FF00";
c.strokeRect(-5, -5, 10, 10);
c.closePath();
c.stroke();
}
}
Exhibit B(创建/删除项目符号的函数):
shoot: function() {
if(engine.keyDown.sp == true) {
if(this.fire > 20) {
engine.bullets.unshift(new Bullet(this.x, this.y, this.rot, this.velocity));
this.fire = 0;
} else {
this.fire++
}
}
for(i = 0; i < engine.bullets.length; i++) {
engine.bullets[i].move();
engine.bullets[i].draw();
if(engine.bullets[i].x > engine.canvas.width+5 || engine.bullets[i].x < -5
|| engine.bullets[i].y > engine.canvas.height+5 || engine.bullets[i].y < -5) {
console.log('bullet gone, '+i);
engine.bullets.splice(i, 1);
}
}
}
数组声明如下:bullets: []
感谢您的任何回答。
【问题讨论】:
-
在
for循环中,每次缩短数组时,都需要注意数组的长度。因此,您可能会考虑将bullets.length分配给一个变量,在循环条件中使用该变量,然后每次从数组中删除项目符号时递减该变量。 -
感谢您的回答,但事实证明,这不是问题所在。我尝试将
context.save();和context.restore();放在子弹发生平移/旋转的位置。现在没有问题 -
@JanProcházka 您应该将其作为答案并将其标记为正确 - 特别是如果您知道为什么这是正确答案并且可以解释它!
-
永远不要在转发
for循环中使用splice。当i-th 元素被splice移除时,所有从i+1到最后一个元素都向左移动并分别改变它们的索引。这就是为什么你会得到不可预测的行为。
标签: javascript arrays push splice