我有一段代码可以添加10个球对象,每个对象都有一个数组(x,xvel,radius等)。在球对象内部,我创建了4个函数:绘图函数,移动函数,鼠标框碰撞函数和球碰撞函数。除了球碰撞功能外,所有这些功能都能成功运行。这是因为当它被添加到执行循环中时,只绘制一个球而其余的球是不可见的。
for(i = 0; i < balls.length;i++)
{
balls[i].move()
balls[i].draw()
balls[i].mouse_collision()
//This function is the reason for my quarrels, if I allow it to execute then no balls are drawn except for one however collisions are detected.
//balls[i].checkbox()
}
尽管如此,仍然可以检测到碰撞,所以我的问题在于弄清楚如何让碰撞和绘图同时工作。复选框功能中使用的代码
this.checkbox = function() {
//Attempt at collision function, loops through all other balls and
//if collision == true then the function executes,
//causing the balls to bounce of each other.
for(i = 0; i < balls.length; i++)
{
if(collision(x,y,radius,balls[i].x,balls[i].y,balls[i].radius) && balls[i].id != id)
{
console.log("COLLISION")
o_xvel = balls[i].xvel
o_yvel = balls[i].yvel
balls[i].xvel = xvel
balls[i].yvel = yvel
xvel = o_xvel
yvel = o_yvel
}
}
}
链接到JSFiddle的代码:https://jsfiddle.net/HatBreakingDad/fnzr51yq/
P.S对不起,如果我的英语不好,因为它不是我的第一语言。
你正在覆盖其他一些i
变量。
限制他们的范围,用let
,var
或const
声明它们。更换
for(i = 0; i < balls.length; i++)
同
for(let i = 0; i < balls.length; i++)
会这样做,例如。
或者你可以重命名它们。