cocos2dx初体验

资源图片

122458972.png

代码 HelloWorldScene.cpp:

    CCSize s = CCDirector::sharedDirector()->getWinSize();
    //
    //#1:生成动画需要的数据类
    CCTexture2D *texture=CCTextureCache::sharedTextureCache()->addImage("122458972.png");
    //
    CCSpriteFrame *frame0=CCSpriteFrame::createWithTexture(texture,CCRectMake(32*0, 48*0, 32, 48));
    CCSpriteFrame *frame1=CCSpriteFrame::createWithTexture(texture,CCRectMake(32*1, 48*0, 32, 48));
    CCSpriteFrame *frame2=CCSpriteFrame::createWithTexture(texture,CCRectMake(32*2, 48*0, 32, 48));
    CCSpriteFrame *frame3=CCSpriteFrame::createWithTexture(texture,CCRectMake(32*3, 48*0, 32, 48));
    //
    CCArray *animFrames = CCArray::create();
    animFrames->addObject(frame0);
    animFrames->addObject(frame1);
    animFrames->addObject(frame2);
    animFrames->addObject(frame3);
    //
    CCAnimation *animation=CCAnimation::createWithSpriteFrames(animFrames,0.2f);
    animFrames->release();
    //
    CCSprite *heroSprite0=CCSprite::createWithSpriteFrame(frame0);
    if(!heroSprite0)
        return false;
    heroSprite0->setPosition(ccp(16,s.height-24));
    addChild(heroSprite0,1);
    CCAnimate *animate=CCAnimate::create(animation);
    heroSprite0->runAction(CCRepeatForever::create(animate));//一直执行下去

或者改成循环:

    CCSize s = CCDirector::sharedDirector()->getWinSize();
    //
    //#1:生成动画需要的数据类
    CCTexture2D *texture=CCTextureCache::sharedTextureCache()->addImage("122458972.png");
    CCArray *animFrames = CCArray::create();
    CCSpriteFrame *frame0 = 0;
    //
    for(int i=0; i<4; i++){="" frame0="CCSpriteFrame::createWithTexture(texture,CCRectMake(32*i," 48*0,="" 32,="" 48));="" animframes-="">addObject(frame0);
    }
    //
    CCAnimation *animation=CCAnimation::createWithSpriteFrames(animFrames,0.2f);
    animFrames->release();
    //
    CCSprite *heroSprite0=CCSprite::createWithSpriteFrame(frame0);
    if(!heroSprite0)
        return false;
    heroSprite0->setPosition(ccp(16,s.height-24));
    addChild(heroSprite0,1);
    CCAnimate *animate=CCAnimate::create(animation);
    heroSprite0->runAction(CCRepeatForever::create(animate));//一直执行下去

编译执行

make
./bin/release/Codejm01

效果:

20131104151530.png

资源来自老G小屋,进行代码升级到coco2d-x 2.2。