We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi all, I've been trying to figure this out all day. I've got an array of bubbles floating on the screen. I'm using the mousePressed function to push bubbles into the array. Now I want to make it so if the cursor is within the bounds of a bubble (its diameter) then instead of pushing new bubbles into the array, it will delete that specific bubble from the array. My current code no longer pushes new bubbles and certainly isn't deleting anything. The problem seems to be with cycling through the array when there are no objects yet inside it, but I don't know how to get past this as I need the loop in order for the program to check the cursor's location in relation to the object in the first place...
function mousePressed(){
for (var j = bang.length-1; j >= 0; j--) {
var distance = dist(mouseX, mouseY, bang[j].x, bang[j].y);
if (distance > bang[j].diameter){
bang.push(new Bigbang(mouseX, mouseY,sounds[Math.round(random(sounds.length-1))]));
}
else if (distance < bang[j].diameter) {
bang.splice(bang[j], 1);
}
console.log("new bubble"+bang);
}
}
big cheers to anyone willing to help me solve this...I guess there is a slightly long-winded logical way around the problem but all of my attempts have failed so far.
Answers
Line 9 is checking the mouse against every bubble in the array. But if the array is zero, no bubble will be added. Adding to this, notice that you are adding the bubble on the same array you are checking. IF you add a bubble, do you know if
bang.length
is being updated on the fly?So what I want to say is that your approach is not the best. What about this?
I left the splice function out as I am not sure what it suppose to do. I have a feeling you can add it as part of the else statement in the last if conditional.
Kf
According to splice()'s reference, its 1st parameter gotta be the Array's target index: https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
However, you're passing to it a BigBang object instead: @-)
bang.splice(bang[j], 1);
Shoulda been something like this, passing the current iterator value as index:
bang.splice(j, 1);
Another possible issue is having both push() & splice() within the same loop. :-SS
Given both mutate the Array's length w/ unpredictable consequences. 8-X
Below's my attempt to split your
for ( ; ; )
loop as 2while ()
loops.1st 1 increments variable pushes in order to establish how many BigBang objects to instantiate for the 2nd loop: *-:)
Thank you both for explaining so well. You’ve transformed my world. Kfrajer, I'd tried using a boolean variable earlier today unsuccessfully, looking at how you've worked it I can see that I wasn't grasping the concept. It works great now.
GoToLoop, I hadn't put much thought to the volatility incurred by having push and splice in the same loop. Separating the loops is such a good idea.
fantastic responses.