javascript - 碰撞检测功能可防止程序在阵列中绘制多个球
问题描述
我有一段代码将 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对不起,如果我的英语不好,因为它不是我的第一语言。
解决方案
您正在覆盖其他一些i
变量。
限制它们的作用域,用let
、var
或声明它们const
。更换
for(i = 0; i < balls.length; i++)
和
for(let i = 0; i < balls.length; i++)
会做,例如。
或者你可以重命名它们。
推荐阅读
- python - Python通过杀死线程停止pydub音频
- node.js - 猫鼬在连接超时之前不会返回任何挂起的东西
- kotlin - Kotlin 继承 - 使用父构造器创建子实例
- splunk - Splunk 查看“_value”不使用 mcatalog
- r - R 中的综合控制方法:“dataprep.out$X1 NULL”
- typescript - 创建将类型化数组转换为其第一个元素的类型
- excel - 我可以在单元格不小于或等于日期的情况下进行 COUNTIFS 吗?
- mqtt - 无法将数据发布到我的本地 mqtt 服务器
- racket - 为什么球拍解释器中的“骗局”与 drracket 中的不同?
- javascript - 如何导入可能有语法错误的模块?