The problem is that using the jQuery selector $('.otherCar')
doesn't actually use all of the elements with that class in this case. When you try to get a specific value from a class selector like that, there is no way for it to return all of the values for each element, and work with your logic, so instead it just gives you one of them.
In this case, you will need to use jQuery's .each()
:
//detect collision for every 2 seconds
window.setInterval(function () {
$('#result').text('False');
$.each($('.otherCar'),function(){
if(collision($('#myCar'), $(this))){
$('#result').text('True');
}
});
}, 200);
Basically, I use all the same code as you did, but I use .each()
to loop through every item in that selector, and then run your collision()
function for each one (using the $(this)
selector to get the current element in the loop)
Before the loop, I reset the result text to say 'False', before continuing on to check the elements. If none are found to be true, this will remain as 'False', and be good to go.
I wrapped the function call in an if()
statement, so if the function returns true, the conditional will evaluate to true, and change the result text to 'True'.