Reputation: 217
I have a list of objects to begin with, and I will be adding new objects to this list if they do not interfere with the objects already contained in the list, (kind of like collision detection). I am trying to create a function that can detect this sort of interference.
I have designed it in such a way as to output 'false' if there is a collision (unintuitively) and 'true' if there is not, since I will be using this result later in an if-statement, and I want it to perform the statement in the case that a collision does not occur. The list is called vertices. There are probably plenty of mistakes, but what I am most confused with is the logic of the Boolean function and how it is carried through the if and for loops.
My desired outcome is that, if the new object interferes with any object already in the list, the function will output 'false', and it will output 'true' if and only if the object does not interfere with any element. However, I do not think my code is doing what I have described here. Does the if take the first result, 'true' or 'false'? Does it only output 'true' if all results are true. I think this is the crux of my problem (I may be mistaken).
There is probably a much more efficient way of doing this (if so, please inform me!), but right now I am actually running through every element already in the list with a for loop, and then writing the collision test with an if statement. My code is below:
function test(x, y, len) {
var k;
for (k=0; k < vertices.length; k++) {
if (((y + len) < (vertices[k][1])) || (y > (vertices[k][1] + vertices[k][2])) || ((x + len) < vertices[k][0]) || (x > (vertices[k][0] + vertices[k][2])))
{
return false
} else
{
return true
}
}
}
It could be that there is something wrong with the collision conditions themselves, (the '... or ... or...'), but I think this is not the case. I think something is wrong with my logic that I have described above. If anyone can give me some explanation which can clear things up, it would be very much appreciated. As you can tell, I'm quite new to this. Thanks!
Upvotes: 2
Views: 62
Reputation: 1250
Move return true
outside the for loop.
Then it will only return true if the loop finishes without finding a result first.
function test(x, y, len) {
var k;
for (k=0; k < vertices.length; k++) {
if (((y + len) < (vertices[k][1])) || (y > (vertices[k][1] + vertices[k][2])) || ((x + len) < vertices[k][0]) || (x > (vertices[k][0] + vertices[k][2])))
{
return false
}
}
return true;
}
Upvotes: 1