sprite我暂时简单理解为一个可以移动的实体,随便什么都可以,就是一张贴图,移动,不过可以变换动作(另一张贴图)。
吐槽一下:cocos2d-x的C++代码写的不是很严谨。
下面我们来看下创建的基本流程:
class HelloWorld : public cocos2d::CCLayerColor
建立场景时会这么做:
bool AppDelegate::applicationDidFinishLaunching() { // initialize director CCDirector *pDirector = CCDirector::sharedDirector(); pDirector->setOpenGLView(CCEGLView::sharedOpenGLView()); // turn on display FPS pDirector->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this pDirector->setAnimationInterval(1.0 / 60); // create a scene. it's an autorelease object CCScene *pScene = HelloWorld::scene(); // run pDirector->runWithScene(pScene); return true; }
那里面要生成精灵嘛:
CCScene* HelloWorld::scene() { CCScene * scene = NULL; do { // 'scene' is an autorelease object scene = CCScene::create(); CC_BREAK_IF(! scene); // 'layer' is an autorelease object HelloWorld *layer = HelloWorld::create(); CC_BREAK_IF(! layer); // add layer as a child to scene scene->addChild(layer); } while (0); // return the scene return scene; }
CCScene *CCScene::create() { CCScene *pRet = new CCScene(); if (pRet && pRet->init()) { pRet->autorelease(); return pRet; } else { CC_SAFE_DELETE(pRet); return NULL; } }
// on "init" you need to initialize your instance bool HelloWorld::init() { if (!CCLayerColor::initWithColor( ccc4(255,255,255,255) )) { return false; } CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCSprite *player = CCSprite::create("Player.png", CCRectMake(0,0,27,40)); player->setPosition(ccp(player->getContentSize().width/2, winSize.height/2)); addChild(player); schedule(schedule_selector(HelloWorld::gameLogic),1.0); return true; }
我们看重要的一句逻辑:
schedule(schedule_selector(HelloWorld::gameLogic),1.0);这句的作用 API有说明:Callback interval time in seconds. 0 means tick every frame, 就是每隔一段时间回调一次。当然我们使用这个回调来产生敌人的。
依次调用的函数有:
void HelloWorld::gameLogic( float dt )
{
addTarget();
}
void HelloWorld::addTarget() { CCSprite* target = CCSprite::create("Target.png", CCRectMake(0,0,27,40)); if (NULL == target) { CCLOG("Create target failed"); return; } CCSize winSize = CCDirector::sharedDirector()->getWinSize(); const int minY = target->getContentSize().height/2; const int maxY = winSize.height-minY; const int rangeY = maxY- minY; const int actualY = (rand()%rangeY)+minY; target->setPosition(ccp(winSize.width+target->getContentSize().width/2, actualY)); addChild(target); const int minDuration = 2; const int maxDuration = 4; const int rangeDuration = maxDuration-minDuration; const int actualDuration = (rand()%rangeDuration)+minDuration; CCFiniteTimeAction* action = CCMoveTo::create((float)actualDuration, ccp(-target->getContentSize().width/2, actualY)); CCFiniteTimeAction* actionMoveDone = CCCallFuncN::create( this,callfuncN_selector(HelloWorld::spriteMoveFinished)); target->runAction(CCSequence::create(action,actionMoveDone,NULL)); }
if (NULL == target) { CCLOG("Create target failed"); return; }源代码是木有的,我认为这是应该的。
上面的代码主要是用来添加敌人,设置动作开始、结束。
好了。大家可以直接去下载代码,编译,享受搞出来可以动弹的画面的快乐吧。