如何在cocos2d-x中使用box2d进行碰撞检测

时间:2012-01-28 05:42:11

标签: collision-detection box2d cocos2d-x marmalade

我的两个精灵是滚动和英雄。我想在cocos2d-x中使用box2d检测它们的碰撞 我已经让两个精灵在屏幕上移动(自动滚动,手动英雄)。

我想做的就是调用函数intersection();

当两个精灵碰撞时。 (精灵在* .h文件中全局声明)

#include "GameScene.h"
#include "HomeScene.h"
USING_NS_CC;

CCScene* GameScene::scene()
{
    // 'scene' is an autorelease object
    CCScene *scene = CCScene::node();

    // 'layer' is an autorelease object
    GameScene *layer = GameScene::node();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool GameScene::init()
{

    //////////////////////////////
    // 1. super init first
    if ( !CCLayerColor::initWithColor(ccc4(0,0,0,255) ))
    {
        return false;
    }

    //////////////////////////////
    // 2. add your codes below...
    count=0;
    life=3;
    CCSize WinSize= CCDirector::sharedDirector()->getWinSize();
    // background
    CCSprite * bg=CCSprite::spriteWithFile("bg.png");
    bg->setPosition(CCPointZero);
    bg->setAnchorPoint(CCPointZero);
    bg->setScaleX(WinSize.width/460);
    bg->setScaleY(WinSize.height/325);
    this->addChild(bg,0,1);

    //close button
    CCSprite * back=CCSprite::spriteWithFile("close.png");
    CCSprite * back1=CCSprite::spriteWithFile("closeS.png");
    CCMenuItemSprite *home=CCMenuItemSprite::itemFromNormalSprite(back,back1,this,menu_selector(GameScene::callNext));
    CCMenu *MenuClose=CCMenu::menuWithItem(home);
    MenuClose->setPosition(ccp(WinSize.width-20,WinSize.height-20));
    this->addChild(MenuClose,5,1);

    //life icon
    CCSprite * rc=CCSprite::spriteWithFile("rc.png");
    rc->setPosition(ccp(20,WinSize.height-20));
    this->addChild(rc,5,15);

    //score icon
    CCSprite * dp=CCSprite::spriteWithFile("dp.png");
    dp->setPosition(ccp(55,WinSize.height-20));
    this->addChild(dp,5,18);

    //insert roller at a random place
    roll=CCSprite::spriteWithFile("ball.png");
    int minY = (roll->getContentSize().height/2)+(WinSize.height/(4.5));
    int maxY = (WinSize.height)-  (roll->getContentSize().height/2);
    int rangeY = maxY - minY;

    srand ( time(NULL) );

    int actualY = ( rand() % rangeY ) + minY;
    CCLOG("the actualY is oooooooooooooooooooooooooooooooooooooooooooooooooooooooo %d",actualY);
    roll->setPosition(ccp(20,actualY));
    this->addChild(roll,5,8);

    // Determine speed of the roller
    int minDuration = 3;
    int maxDuration = 7;
    int rangeDuration = maxDuration - minDuration;
    int actualDuration = ( rand() % rangeDuration)+ minDuration;

/*  
//creating constraints for the roller
float maxXX = WinSize.width - roll->getContentSize().width/2;
float minXX =roll->getContentSize().width/2;
if (roll->getPosition().x > maxXX)
{
    roll->setPosition( ccp(maxXX, roll->getPosition().y)) ;
}
else if (roll->getPosition().x < minXX)
{
     roll->setPosition (ccp(minXX,roll->getPosition().y));
}


float maxYY = WinSize.height - roll->getContentSize().height/2;
float minYY = roll->getContentSize().height/2;

if (roll->getPosition().y > maxYY)
{
   roll->setPosition ( ccp(roll->getPosition().x, maxYY));
}
else if (getPosition().y < minYY)
{
   roll->setPosition( ccp(roll->getPosition().x, minYY));
}
*/


    // Create the rolling action   
    roll->runAction(CCRepeatForever::actionWithAction((CCSequence*) CCSequence::actions(
                    CCJumpTo::actionWithDuration( actualDuration,ccp(WinSize.width,( rand() % rangeY ) + minY ),( rand() % rangeY ) + minY,4 ),
                    CCHide::action(), 
                    CCMoveTo::actionWithDuration(0,ccp(20,( rand() % rangeY ) + minY)),
                    CCShow::action(), 
                    CCCallFunc::actionWithTarget( this,callfunc_selector(GameScene::scores)),
                    NULL)) );

    //displaying scores
    sprintf(score,"%d",count);  
    scr= CCLabelBMFont::labelWithString(score , "arial16.fnt");
    scr->setPosition(ccp(55,WinSize.height-20));
    scr->setColor(ccc3(0,0,255));
    this->addChild(scr,50);

    //displaying lifes
    sprintf(lifeLabel,"%d",life);   
    lif= CCLabelBMFont::labelWithString(lifeLabel , "arial16.fnt");
    lif->setPosition(ccp(20,WinSize.height-20));
    lif->setColor(ccc3(0,0,255));
    this->addChild(lif,50);

    // insert animated hero
    CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile("boyJog.plist","boyJog.png");

    CCMutableArray<CCSpriteFrame*> *proFrame = new CCMutableArray<CCSpriteFrame *>;
    hero = CCSprite::spriteWithSpriteFrameName("boyJog1.png");
    hero->setPosition(ccp(WinSize.width/2-30,WinSize.height/(4.5)));
    hero->setAnchorPoint(CCPointZero);

    char buff[60];
    for(int i=1;i<=13;i++)
    {
        sprintf(buff,"boyJog%d.png",i);
        proFrame->addObject( (CCSpriteFrameCache::sharedSpriteFrameCache())->spriteFrameByName(buff));
    }

    CCAnimation *progressAnimation=CCAnimation::animationWithFrames(proFrame, 0.05);

    //set animation object here
    CCAnimate *animate=CCAnimate::actionWithAnimation(progressAnimation,false); 
    hero->runAction(CCRepeatForever::actionWithAction(animate));
    hero->setScale(.5);

    this->addChild( hero);




    //left right button
    CCSprite *moveRight= CCSprite::spriteWithFile("arrowRight.png");
    CCSprite *moveLeft= CCSprite::spriteWithFile("arrowLeft.png");
    CCSprite *moveRightS= CCSprite::spriteWithFile("arrowRight.png");
    CCSprite *moveLeftS= CCSprite::spriteWithFile("arrowLeft.png");

    CCMenuItemSprite *right=CCMenuItemSprite::itemFromNormalSprite(moveRight,moveRightS,this,menu_selector(GameScene::heroRight));
    CCMenuItemSprite *left=CCMenuItemSprite::itemFromNormalSprite(moveLeft,moveLeftS,this,menu_selector(GameScene::heroLeft));
    CCMenu *RL =CCMenu::menuWithItems(left,right,NULL);

    RL->alignItemsHorizontallyWithPadding(20);
    RL->setPosition(ccp(WinSize.width-40,20));
    RL->setOpacity(150);
    this->addChild(RL);


    //jump button
    CCSprite *jump= CCSprite::spriteWithFile("arrowUp.png");
    CCSprite *jumpS= CCSprite::spriteWithFile("arrowUp.png");
    CCMenuItemSprite *mmJump=CCMenuItemSprite::itemFromNormalSprite(jump,jumpS,this,menu_selector(GameScene::heroJump));
    CCMenu *menuJump=CCMenu::menuWithItem(mmJump);
    menuJump->setPosition(ccp(20,20));

    menuJump->setOpacity(150);

    this->addChild(menuJump,5,12);




    //////////////////////////////
    return true;
}


void GameScene::callNext(CCObject *sender)
{
    CCLOG("game played");

    CCDirector::sharedDirector()->replaceScene(CCTransitionFade::transitionWithDuration(1,(HomeScene::scene())));
    //exit(1);
}

void GameScene::heroJump(CCObject *sender)
{
    CCLOG(" U");
    CCSize WinSize= CCDirector::sharedDirector()->getWinSize();
    CCPoint Pt=hero->getPosition();
    hero->runAction(CCJumpTo::actionWithDuration(1,ccp(Pt.x,WinSize.height/(4.5)),50,1));
}
void GameScene::heroLeft(CCObject *sender)
{
    CCLOG(" L");
    CCSize WinSize= CCDirector::sharedDirector()->getWinSize();
    CCPoint Pt=hero->getPosition();
    hero->runAction(CCJumpTo::actionWithDuration(1,ccp(Pt.x-30,WinSize.height/(4.5)),0,1));
    hero->setFlipX(1);
    //hero->runAction(CCRepeatForever::actionWithAction(animate));

}
void GameScene::heroRight(CCObject *sender)
{
    CCLOG(" R");
    CCSize WinSize= CCDirector::sharedDirector()->getWinSize();
    CCPoint Pt=hero->getPosition();
    hero->runAction(CCJumpTo::actionWithDuration(1,ccp(Pt.x+30,WinSize.height/(4.5)),0,1));
    hero->setFlipX(0);
    //hero->runAction(CCRepeatForever::actionWithAction(animate));
}

void GameScene::scores()
{

    count+=10;
    CCLOG("count ==========================%d",count);
    sprintf(score,"%d",count);
    scr->setString(score);
}

void GameScene::intersection()
{
    CCLOG("collided..........................................................");
}

3 个答案:

答案 0 :(得分:4)

Sprited没有碰撞。你必须使用Box2D,同步图形和物理创建他们的物理表示。然后你必须实现自己的联系人监听器(继承自b2ContactListener)并使用它在发生冲突时得到通知。

答案 1 :(得分:2)

您必须为要应用Bodies的每个对象创建box2D collision。身体必须有fixtures,因为固定装置是碰撞的,而不是身体。

请检查this tutorial以获取box2d。

修改

添加:Sprites只是图像,他们不知道物理。它们必须附着在带有固定装置的物体上。所以他们知道那里有一些其他的精灵,他们需要像碰撞一样对碰撞做出反应,或者只是摧毁另一个精灵。

答案 2 :(得分:0)

在我看来,this tutorial更有帮助。 如果您不希望角色在碰撞时反弹但仍然检测到碰撞,请将其灯具设置为传感器。 如果您不希望它们发生碰撞,请将它们的fixture groupIndex设置为相同的整数(更好的负数)。

yourFixtureDef.filter.groupIndex = -1; // for example