user1059511
user1059511

Reputation: 267

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?

Upvotes: 0

Views: 540

Answers (2)

Master Slave
Master Slave

Reputation: 28519

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/

Upvotes: 1

chead23
chead23

Reputation: 1879

Try something like:

$.each($('.tree'), function(tree){
    treeHit = hitTest(sled, tree);
    return treeHit;
});

Upvotes: 0

Related Questions