Search code examples
c++visual-c++collision-detectioncocos2d-xmarmalade

Ensure collision detection triggers only once per collision


I am trying collision detection without using Box2d, so i used a inbuilt function CCRectIntersectsRect() using this function when i decrement the count it gets reduced to negative values in a single collision. (when the ball touches hero and when the ball crosses hero.)

All i want is to schedule it in someway so that the count-- gets called once only.

For complete source code how to use box2d for collision detection in cocos2d-x

CCRect bom= ball->boundingBox();
CCRect gon= hero->boundingBox();

if(CCRect::CCRectIntersectsRect(bom,gon))
{
    count--;
}

Solution

  • Create a persistent bool variable called colliding, and use it like this:

    if(CCRect::CCRectIntersectsRect(bom,gon))
    {
        if (!colliding)
            count--;
        colliding = true;
    }
    else
        colliding = false;
    

    Here's the fix for the code you provided in the comments below:

    CCRect bom= roll->boundingBox();
    CCRect gon= hero->boundingBox();
    static bool colliding=false;
    if(CCRect::CCRectIntersectsRect(bom,gon))
    {
        if (!colliding)
        {
            intersection();
            colliding = true;
        }
    }
    else
        colliding = false;