Cocos2d-X 游戏之碰撞检测的方法

时间:2022-06-06 04:56:54

// 碰撞检测 第一种

bool Tools::iscollision(CCSprite *sprite1,CCSprite *sprite2)

{

    CCPoint point1 =sprite1->getPosition();

    CCPoint point2 =sprite2->getPosition();

    CCSize point1Size=  sprite1->getContentSize();

    CCSize point2Size=  sprite2->getContentSize();

    if(abs(point1.x-point2.x) <=point1Size.width/2 +point2Size.width/2&&abs(point1.y-point2.y) <=point1Size.height/2 +point2Size.height/2)

        return true;

    return false;

}

// 碰撞检测 第2

bool GameLayer::pengLeft(CCRectbirdBox, CCRect barbox)

{

    CCPoint targetPoint =ccp(birdBox.getMinX(), birdBox.getMidY());

    returnbarbox.containsPoint(targetPoint);

}

//碰撞检测 第3种

 bool AA::iscallision(CCSprite*mysprite,CCSprite *testsprite)

 

{

 

   CCRect myrect=mysprite->boundingBox();

    CCRect testrect=testsprite->boundingBox();

 return myrect.intersectsRect(testrect);

}

//碰撞检测第三种

//是否碰撞

boolHaiGameLayer::isCollsion(CCSprite *sp1,CCSprite *sp2)

{

    CCRect myRect =getRect(sp1);

    CCRect testRect =getRect(sp2);

    return  myRect.intersectsRect(testRect);

}

//获取精灵的rect

CCRectHaiGameLayer::getRect(CCSprite *sprite)

{

    CCSize s = sprite->getContentSize();

    CCPoint p = sprite->getPosition();

    CCPoint ap = sprite->getAnchorPoint();

    CCRect rect =CCRectMake( p.x - ap.x * s.width , p.y - ap.y * s.height,s.width, s.height);

    return rect;

}

 //碰撞检测

voidHaiGameLayer::tection()

{

    for(int i=0;i<fishArray->count();i++)

    {

        CCSprite *s=(CCSprite *)fishArray->objectAtIndex(i);

        if(isCollsion(sp1, s))

        {

            CCLog("shibai");

        }

    }

}