目标:想要精灵进行随机的移动。
过程:需要一个白色的背景,所以先来修改 HelloWorld 的继承,改成继承 CCLayerColor,然后修改一下 init 方法。如下:
CCLayerColor::initWithColor(ccc4(255, 255, 255, 255))
HelloWorld.h 声明的方法:
void addTarget(); void spriteMoveFinished(CCNode *sender); void gameLogic(cocos2d::CCTime dt);
#include "HelloWorldScene.h" #include "SimpleAudioEngine.h" using namespace cocos2d; using namespace CocosDenshion; CCScene* HelloWorld::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object HelloWorld *layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if ( CCLayerColor::initWithColor(ccc4(255, 255, 255, 255)) ) { CCSize winSize = CCDirector::sharedDirector()->getWinSize();//获取屏幕大小 float sprite_scale = 2.0; CCSprite *Player = CCSprite::create("Player.png"); Player->setScale(sprite_scale); Player->setPosition(ccp(Player->getContentSize().width*sprite_scale/2.0, winSize.height/2.0)); this->addChild(Player); this->schedule(schedule_selector(HelloWorld::gameLogic), 1.0); return true; } else{ return false; } } void HelloWorld::gameLogic(cocos2d::CCTime dt){ this->addTarget(); } void HelloWorld::addTarget(){ CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCSprite *target = CCSprite::create("Target.png"); //随机位置 int minY = target->getContentSize().height/2.0; int maxY = winSize.height - target->getContentSize().height/2.0; int rangeY = maxY - minY; int actualY = rand()%rangeY + minY; target->setPosition(ccp(winSize.width - target->getContentSize().width/2.0, actualY)); this->addChild(target); //随机速度 float minDuration = 2.0; float maxDuration = 4.0; int rangeDuration = maxDuration - minDuration; float actualDuration = rand()%rangeDuration + minDuration; CCFiniteTimeAction *actionMove = CCMoveTo::create(actualDuration, ccp(0 - target->getContentSize().width/2.0, actualY));//0代表屏幕外,这句表示在3秒内从初始位置移动到屏幕外 //增加一个回调函数,回收移动到屏幕外的精灵 CCFiniteTimeAction *actionMoveDone = CCCallFuncN::create(this, callfuncN_selector(HelloWorld::spriteMoveFinished)); target->runAction(CCSequence::create(actionMove,actionMoveDone,NULL)); } void HelloWorld::spriteMoveFinished(cocos2d::CCNode *sender){ CCSprite *sprite = (CCSprite *)sender; this->removeChild(sprite, true); } void HelloWorld::menuCloseCallback(CCObject* pSender) { CCDirector::sharedDirector()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }