Rect/Bounding Box Collision

Detect Collision Between Two Nodes

Rect collision is a really easy way of detecting when two objects have overlapped each other.

Rect rect1 = node1->getBoundingBox( );
Rect rect2 = node2->getBoundingBox( );

if ( rect1.intersectsRect( rect2 ) )
{
    log( "Collided" );
}
else
{
    log( "Not collided" );
}
var rect1 = node1.getBoundingBox( );
var rect2 = node2.getBoundingBox( );

if ( cc.rectIntersectsRect( rect1, rect2 ) )
{
    cc.log( "Collided" );
}
else
{
    cc.log( "Not collided" );
}

Detect When A Node Has Been Touched

Rects can be used to easily detect when a node has been touched by the user.

bool HelloWorld::onTouchBegan(cocos2d::Touch *touch, cocos2d::Event *event)
{
    Rect rect1 = node->getBoundingBox( );
    Point touchPoint = touch->getLocation( );
    
    if ( rect1.containsPoint( touchPoint ) )
    {
        log( "Touched" );
    }
    else
    {
        log( "Not touched" );
    }
    
    return true; // true if the function wants to swallow the touch
}
onTouchBegan:function( touch, event )
{
    var rect1 = node1.getBoundingBox( );
    var touchPoint = touch.getLocation( );
    if ( cc.rectContainsPoint( rect1, touchPoint ) )
    {
        cc.log( "Touched" );
    }
    else
    {
        cc.log( "Not touched" );
    }
    
    return true;
},

Note: This example uses onTouchBegan but any interaction method can be used.