Rectangle + Rectangle HitTest Example

Quick HitTest example for Marco...

by soulwire

HTML

<div class="box boxA"></div>
<div class="box boxB"></div>

CSS

.box {
    opacity: 0.8;
    position: absolute;
    display: block;
    box-shadow: 1px 2px 4px rgba(0,0,0,0.1);
    border: 1px solid rgba(255,255,255,0.9);
    font-family: Arial, Helvetica, sans-serif;
    text-transform: uppercase;
    text-align: center;
    font-size: 38px;
    color: #fff;
}

.boxA {
    background: #DEF16D;
    height: 100px;
    width: 100px;
    left: 200px;
    top: 180px;
}

.boxB {
    background: #25C8D9;
    line-height: 120px;
    height: 120px;
    width: 180px;
}

JavaScript

/*
    Returns the bounding rectangle of a jQuery element
    {x,y,w,h}
*/
function getBounds(el) {
    var pos = el.position();
    return {
        x: pos.left,
        y: pos.top,
        w: el.width(),
        h: el.height()
    };
}

/*
    Checks for overlap on two rectangles
*/
function hitTest(rectA, rectB) {
    
    var rA = rectA.x + rectA.w; // Right side of rectA
    var rB = rectB.x + rectB.w; // Right side of rectB
    var bA = rectA.y + rectA.h; // Bottom of rectA
    var bB = rectB.y + rectB.h; // Bottom of rectB
    
    var hitX = rA > rectB.x && rectA.x < rB; // True if hit on x-axis
    var hitY = bA > rectB.y && rectA.y < bB; // True if hit on y-axis
    
    // Return true if hit on x and y axis
    return hitX && hitY;
}

var $boxA = $('.boxA');
var $boxB = $('.boxB');

var rectA = getBounds($boxA);
var rectB = getBounds($boxB);

$(document).bind('mousemove', function(e){
    
    // Update rectB position
    rectB.x = e.clientX - $boxB.width() / 2;
    rectB.y = e.clientY - $boxB.height() / 2;
    
    // Update the element position (just for visual debugging)
    $boxB.css({
        left: rectB.x,
        top: rectB.y
    });
    
    // Perform a hittest on rectA and rectB
    var hit = hitTest(rectA, rectB);
    
    // Style the moving box to show hit status
    $boxB.css('background', hit ? '#C11168' : '#25C8D9');
    $boxB.text(hit ? 'Hit' : '');
});