Cocos2d-x 3.2 - Step by Step Cocos2dxSimpleGame Series
在上一篇 Cocos2d-x 3.2 - Chapter 2 - How to Add a sprite 中,我們已經增加了一位英雄。但是英雄只有一個人太孤單了,所以我們來增加一些敵人。
addTarget() 這個函式會讓敵人隨機的出現,並從右向左移動。
void HelloWorld::addTarget()
{
Sprite *target = Sprite::create("Target.png", Rect(0, 0, 27, 40));
// Determine where to spawn the target along the Y axis
Size winSize = Director::getInstance()->getWinSize();
int minY = target->getContentSize().height / 2;
int maxY = winSize.height - target->getContentSize().height / 2;
int rangeY = maxY - minY;
// srand( TimGetTicks() );
int actualY = (rand() % rangeY) + minY;
// Create the target slightly off-screen along the right edge,
// and along a random position along the Y axis as calculated
target->setPosition(Point(winSize.width + (target->getContentSize().width / 2), actualY));
this->addChild(target);
// Determine speed of the target
int minDuration = (int)2.0;
int maxDuration = (int)4.0;
int rangeDuration = maxDuration - minDuration;
// srand( TimGetTicks() );
int actualDuration = (rand() % rangeDuration) + minDuration;
// Create the actions
FiniteTimeAction* actionMove =
MoveTo::create((float)actualDuration,
Point(0 - target->getContentSize().width / 2, actualY));
FiniteTimeAction* actionMoveDone =
CallFuncN::create(std::bind(&HelloWorld::spriteMoveFinished, this, std::placeholders::_1));
target->runAction(Sequence::create(actionMove, actionMoveDone, NULL));
}
其中 CallFuncN::create(std::bind(&HelloWorld::spriteMoveFinished, this, std::placeholders::_1)) 使用了回呼函式,所以我們需要宣告 spriteMoveFinished 函式在 HelloWorld。
void HelloWorld::spriteMoveFinished(Node* sender)
{
Sprite *sprite = (Sprite *)sender;
this->removeChild(sprite, true);
}
接著,我們需要定時讓敵人出現在場景上,加入下列這段程式到 init 函中的 return 之前
this->schedule(schedule_selector(HelloWorld::gameLogic), 1.0);
然後實作 gameLogic() 函式
void HelloWorld::gameLogic(float dt)
{
this->addTarget();
}
好了,所有的工作都完成了,建置然後看看結果吧:
參考資料:
Cocos2d-x
http://www.cocos2d-x.org/
Step by Step Cocos2dxSimpleGame Series (Old Version for cocos2d-x v2.x)
http://www.cocos2d-x.org/wiki/Step_by_Step_Cocos2dxSimpleGame_Series
沒有留言:
張貼留言