Hit detection issue

102 views Asked by At

I can't figure out why this hit detection won't work. I've tried changing the >, and the width/height values, but get no working result. I've placed a println() function inside the detection to ensure its not the functions inside that aren't working.

Code:

for(var b = 0; b < particles.length; b++) {
    if(particles[a] === particles[b]) {
        b++;    
    /*particle[a][3] OR particle[b][3] shows the x point.*/
    /*particle[a][4] OR particle[b][4] shows the y point.*/
    /*a is defined in a for loop just like the for loop above (for b).*/
    } else if(particles[a][3]+10 > particles[b][3] && particles[a][3]-10 < particles[b][3] && particles[a][4]+10 > particles[b][4] && particles[a][4]+10 < particles[b][4]) {
        var temp = particles[a][5];
        particles[a][5] = particles[b][5];
        particles[b][5] = temp;
        println("hi");
     }
}

Little bit more backstory to the project. Basically I have a array with a list of points ("particles") and I want them to have a hit detection system so they bounce off each other and head in opposite directions.

Any help would be appreciated!


Final working code:

for(var b = 0; b < particles.length; b++) {
    if(a !== b && particles[a][3] > particles[b][3]-10 && particles[a][3] < particles[b][3]+10 && particles[a][4] > particles[b][4]-10 && particles[a][4] < particles[b][4]+10) {
        var temp = particles[a][5];
        particles[a][5] = particles[b][5];
        particles[b][5] = temp;
        println("hi");
    }
 }
1

There are 1 answers

1
Jaromanda X On BEST ANSWER

firstly, particles[a] === particles[b] means, and can only be true when a === b

secondly, when particles[a] === particles[b] you increment b, then the for loop increments b again ... means you miss a particle!!

try this:

for(var b = 0; b < particles.length; b++) {
    if(a === b) {
        continue;    
    } else if(particles[a][3]+10 > particles[b][3] && particles[a][3]-10 < particles[b][3] && particles[a][4]+10 > particles[b][4] && particles[a][4]+10 < particles[b][4]) {
        var temp = particles[a][5];
        particles[a][5] = particles[b][5];
        particles[b][5] = temp;
        println("hi");
     }
}

or even

for(var b = 0; b < particles.length; b++) {
    if (a !== b && particles[a][3]+10 > particles[b][3] && particles[a][3]-10 < particles[b][3] && particles[a][4]+10 > particles[b][4] && particles[a][4]+10 < particles[b][4]) {
        var temp = particles[a][5];
        particles[a][5] = particles[b][5];
        particles[b][5] = temp;
        println("hi");
     }
}