I have a piece of code that adds 10 ball objects, each with individual values (x, xvel, radius etc) to an array. Inside the ball object I have created 4 functions: a draw function, movement function, mouse box collision function and a ball collision function. All these functions work successfully except for the ball collision function. This is because when it is added to the execution loop only one ball is drawn and the rest of the balls are invisible.
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()
}
Despite this however, collision are still detected, so my problem is in figuring out how to get both the collision and drawing working at the same time. Code used in checkbox function
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
}
}
}
Link to code at JSFiddle: https://jsfiddle.net/HatBreakingDad/fnzr51yq/
PS Sorry if my English was bad as it is not my first language.
You're overwriting some other i
variable.
Restrain their scopes, declaring them with let
, var
, or const
. Replacing
for(i = 0; i < balls.length; i++)
with
for(let i = 0; i < balls.length; i++)
will do, for example.
Or you can just rename them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.