首页 > 解决方案 > 碰撞检测功能可防止程序在阵列中绘制多个球

问题描述

我有一段代码将 10 个球对象添加到数组中,每个对象都有单独的值(x、xvel、半径等)。在球对象内部,我创建了 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/

PS对不起,如果我的英语不好,因为它不是我的第一语言。

标签: javascriptfunctioncollision

解决方案


您正在覆盖其他一些i变量。

限制它们的作用域,用letvar或声明它们const。更换

for(i = 0; i < balls.length; i++)

for(let i = 0; i < balls.length; i++)

会做,例如。

或者你可以重命名它们。


推荐阅读