Cocos2d-x学习笔记(三) —— 如何移动精灵
我们在Cocos2d-x学习笔记(二) —— 如何添加一个精灵中,为游戏场景添加了一个精灵。但一个英雄或许太过孤单,我们应该加入一些敌人,让他来打败。
void addTarget()函数将会帮我们完成这一工作,敌人将会以随机的速度,从游戏场景右移动到左。
在HelloWorldScence.h里声明void addTarget(),并在HelloWorldScene.cpp里添加以下的代码,(请不要忘记在HelloWorldScene.cpp的开头加入using namespace cocos2d)
1 void HelloWorld::addTarget() 2 { 3 CCSprite *target = CCSprite::spriteWithFile("Target.png"); 4 5 CCSize winSize = CCDirector::sharedDirector()->getWinSize(); 6 float minY = target->getContentSize().height/2; 7 float maxY = winSize.height - target->getContentSize().height/2; 8 int rangeY = (int)(maxY - minY); 9 int actualY = (rand() % rangeY) + (int)minY; //取得随机Y轴坐标 10 11 //设置目标精灵的初始位置 12 target->setPosition(ccp(winSize.width + (target->getContentSize().width/2),actualY)); 13 //将目标精灵添加到此场景中 14 this->addChild(target); 15 16 int minDuration = (int)2.0; 17 int manDuration = (int)4.0; 18 int rangeDuration = manDuration - minDuration; 19 //取得随机的速度 20 int actualDuration = (rand() % rangeDuration) + minDuration; 21 22 //建立从右往左移动的动作 23 CCFiniteTimeAction *actionMove = CCMoveTo::actionWithDuration((ccTime)actualDuration, 24 ccp(0 - target->getContentSize().width/2,actualY)); 25 CCFiniteTimeAction *actionMoveDown = CCCallFuncN::actionWithTarget(this, 26 callfuncN_selector(HelloWorld::spriteMoveFinished)); 27 target->runAction(CCSequence::actions(actionMove,actionMoveDown,NULL)); 28 }
这里用callfuncN_selector(HelloWorld::spriteMoveFinished)回调了spriteMoveFinished方法,我们需要在HelloWorldScene.h里声明并如下来定义它,
1 void HelloWorld::spriteMoveFinished(CCNode *sender) 2 { 3 CCSprite *sprite = (CCSprite *)sender; 4 this->removeChild(sprite,true); 5 }
要点
1. 关于随机函数。srand和rand是C标准库函数。对于每一个平台来说,你可以先获取毫秒级时间来得到一个随机数。在沃Phone上,这个函数是TimGetTickes(),而在iPhone上,你可以直接通过arc4random()函数来获得随机数。
2. Objc中的YES和NO,在cpp中变为true和false。
3. 回调函数,在objc中用selector:@selector(spriteMoveFinished),但在cpp中实现就比较复杂了,你可以参考cocos2dx\include\selector_protocol.h里的声明。一共有5种回调函数类型
schedule_selector
callfunc_selector
callfuncN_selector
callfuncND_selector
menu_selector
如何使用它们,根据所用函数的定义来决定。比如使用CCTimer::initWithTarget函数,它的第二个参数是SEL_SCHEDULE类型,到selector_protocol.h里查一下,可以看到对应的是schedule_selector(_SELECTOR)宏,所以调用时就需要在类里头实现一个void MyClass::MyCallbackFuncName(ccTime)函数,然后把schedule_selector(MyClass::MyCallbackFuncName)作为CCTimer::initWithTarget的第二个参数传入。
之后,我们应该定时地为游戏加入敌人,把以下代码加入到init()函数的返回值前。
//定时加入敌人 this->schedule(schedule_selecto(HelloWorld::gameLogic),1.0);
然后在HelloWorldScence.cpp里实现gameLogic()。
void HelloWorld::gameLogic(ccTime dt) { this->addTarget(); }
最后在HelloWorldScence.h里声明这些方法
public: void spriteMoveFinished(CCNode* sender); void gameLogic(cocos2d::ccTime dt); private: void addTarget();
好了,所有事情都做完了,编译并运行,好好享用你的成果。如下图所示:
posted on 2012-07-21 00:15 〃ωǒ系﹄条噚氺dē魚ぐ 阅读(807) 评论(0) 收藏 举报