Search code examples
c++iosxcode4cocos2d-x

How to make a sprite jump like a frog in cocos2d-x ios game using c++


I am trying to make a sprite as a frog which will come from the top of the screen and will go downwards to the bottom at y axis =0.Its working fine as a normal CCMoveTo but i want that after a jump the frog should rest for 1 second then again jump.Some kind of delay in moving.Can anyone tell me with this.I am attaching my code also. my frog animations are from fly1.png to fly5.png.I just want a delay after each move or we can say that I just want to call the CCMove after 1 second delay each time until the frog reaches the y axis=0 Any help will be appreciated.Thanks

#include "HelloWorldScene.h"
#include "SimpleAudioEngine.h"
using namespace cocos2d;
using namespace CocosDenshion;

CCScene* HelloWorld::scene()
{

CCScene *scene = CCScene::create();

HelloWorld *layer = HelloWorld::create();

scene->addChild(layer);

return scene;
}


bool HelloWorld::init()
{

if ( !CCLayer::init() )
{
    return false;
}
CCSize winSize=CCDirector::sharedDirector()->getWinSize();

_bgNode = CCNode::create();
_bgNode->setPosition(ccp(winSize.width/2, winSize.height/2));
this->addChild(_bgNode, -1);

_bgSprite = CCSprite::create("bg_2.jpg");
_bgNode->addChild(_bgSprite);

float rX = winSize.width/_bgSprite->getContentSize().width;
float rY = winSize.height/_bgSprite->getContentSize().height;

_bgNode->setScaleX(rX);
_bgNode->setScaleY(rY);

z=CCSprite::create("fly1.png");
z->setScaleX(rX);
z->setScaleY(rY);
z->setPosition(ccp(winSize.width/2,winSize.height+1));
this->addChild(z);
CCAction *a=CCRepeatForever::create(HelloWorld::getAnimationWithFrames(1,5));
z->runAction(a);

z->runAction(CCSequence::create(CCMoveTo::create(2.0, ccp(winSize.width/2, 0)), CCCallFuncN::create(this, callfuncN_selector(HelloWorld::setInvisible)), NULL));

return true;
}

cocos2d::CCAnimate* HelloWorld::getAnimationWithFrames(int from, int to)
{
CCArray* frames = CCArray::create();


for (int i = from; i <= to; i++)
{
    CCString *str = CCString::createWithFormat("fly2%d.png", i);
    CCSpriteFrame *f = CCSpriteFrame::create(str->getCString(), CCRect(0,0,256,400));
    frames->addObject(f);
}
//(frames,speedofmovementofanimation);
CCAnimation *animation = CCAnimation::createWithSpriteFrames(frames,0.15f);

CCAnimate *a = CCAnimate::create(animation);
return a;
}

void HelloWorld::setInvisible()
{
this->removeChild(z,true);
}

Solution

  •         Firstly, you have to create a frogJump() function. Then,in frogJump() function add the following code:
    
            void HelloWorld::frogJump()
    
            {
    
            CCJumpTo* jumpTo = CCJumpTo::create(1,ccp(x/6,y/8),y/1.2f,1);
    
            z->runAction(jumpTo);
    
            }
    
            Then, in the init() function add the following line:
    
    
           this->scheduleOnce(SEL_SCHEDULE(&HelloWorld::frogJump),0);
      this->schedule(SEL_SCHEDULE(&HelloWorld::frogJump),2);