Search code examples
jquerycollision-detectionhittest

reusable hit test / collision detection


I have a set interval that checks if my sled hits a tree.

var sled =  $("#sled") 
var tree =  $(".tree")

var hitting = setInterval(function() {
var treeHit = hitTest(sled,tree )
if (treeHit == true ) {
    gameOver()
}

}, 1);

Which calls my hitTest function that returns true or false.

function hitTest(a, b) { 
var aTop = a.offset().top;
var aLeft = a.offset().left;
var bTop = b.offset().top;
var bLeft = b.offset().left;

return !(
    ((aTop + a.height()) < (bTop)) ||
    (aTop > (bTop + b.height())) ||
    ((aLeft + a.width()) < bLeft) ||
    (aLeft > (bLeft + b.width()))
);
}

This works fine, but only for the first dom element with the class "tree" (I have multiple), I am not sure why it would not work for all?


Solution

  • Definitely an issue with the array instead of an element. I would change the function to

        var hitting = setInterval(function () {
            var treeHit = false;
            $('.tree').each(function () {
                treeHit = hitTest(sled, $(this));
                if (treeHit == true) {
                    console.log('hit');
                }
            });
        }, 1);
    

    Here is a working fiddle

    http://jsfiddle.net/11cb5s74/