Reputation: 2190
I have a strange bug happening in my script. I have 3 balls on the canvas, and I can click on anyone of them to select.
If I click another ball after one was selected, the new ball gets selected. Everytime a new ball is selected, the array of selected balls gets reset. So far so good.
What I would like to do is to reset the array of selected balls when I click on the empty space inside canvas.
But this only works for 1 of the balls (The bottom one, index # 2 in array). But if I turn on alert to see what ball was clicked, all balls record the click. And since I get the alert window pop up and the script freezes, I can see that the other balls are briefly selected aswell.
I have made this jsFiddle for you to look at. When you first load the fiddle the code that bugs is commented out, uncomment it see it.
The piece of code to look for is:
function selectBall(){
var mX = mouseX;
var mY = mouseY;
for(i=0;i<balls.length;i++){
if(balls[i].select(mX, mY)){
ball.length = 0;
ball.push(balls[i]);
/* Uncomment this to see that click actually happens.
alert('Ball ' + i + ' clicked');
*/
}
/* Uncomment this to get the bug.
else {
ball.length = 0;
}
*/
}
}
Why do I get this bug when the same line of code resets the array just fine when it's inside the if statement but not when its under else?
How can I fix it?
Upvotes: 2
Views: 82
Reputation: 5664
You are restting the ball list for every ball that is not clicked. This is incorrect. What you want to do is only reset the ball list if no balls were clicked. This can be fixed with the following.
function selectBall(){
var mX = mouseX;
var mY = mouseY;
var isClick = false;
for(i=0;i<balls.length;i++){
if(balls[i].select(mX, mY)){
isClick = true;
ball.length = 0;
ball.push(balls[i]);
break;
}
}
if (!isClick)
{
ball.length = 0;
}
}
You can see that I added a simple flag to determine if any balls were selected or not. If none were, then I reset the array. Otherwise, I do not reset the array.
Upvotes: 1