[Set Top] cocos2d-x 3.0 Game Development xcode5 Handshake Blog Teaching 004.[HoldTail] The hero flies up and down to follow the movement...

Original Link: http://www.cnblogs.com/riasky/p/3465140.html

cocos2d-x 3.0 Game Development xcode5 Handshake Blog Teaching 004.[HoldTail] The hero flies up and down and moves

Preface to you, when learning cocos2d-x, I took a lot of detours and encountered a lot of problems. Whether it is simple or difficult, I have slowly overcome them step by step now. In fact, making games with cocos2d-x is very simple. Don't be scared by making games, support me to open source gamesThe reason is because of the support from all of you in eoe Shanghai.Go on, go on, to illustrate, please include more if you write poorly.I'm sure you'll succeed if you follow my blog step by step.


I'm glad to see some friends do this with me so that I have the confidence to write down. Come on, everyone. The protagonist has been writing for a few days without updating. Today, we send updates to you. Next time, we update the comments of See Home.


Okay, back to the point, starting today with the control of the hero's up and down movement

Effect Picture





First add the protagonist class

SWGamePlayer.h

 

//
//  SWGamePlayer.h
//  Holdtail
//
//  Created by Hand Print on 13-12-04.
//
//

#ifndef __Holdtail__SWGamePlayer__
#define __Holdtail__SWGamePlayer__

#include <iostream>
#include <sstream>
#include "cocos2d.h"
#include "cocos-ext.h"

using namespace cocos2d;
using namespace std;
using namespace extension;

//Type conversion class int.float --> String
template<typename T>
string Convert2String(const T & value){
    stringstream ss;
    ss << value;
    return ss.str();
}

//Define the type of enumeration for pictures
typedef enum{
    tag_player_up,
    tag_player_down,
    tag_player_fly,
    tag_player_run,
    tag_playerHp,
}tagPlayers;


class SWGamePlayer:public cocos2d::Sprite{
public:
    static SWGamePlayer *createPlayer(const char *fileName,int allCount,float sprit);
    //Lower the hero's blood volume
    void downHp(float _value);
    int hp;//Blood Volume
    int hpMax;//Maximum blood volume
    static SWGamePlayer *sharedPlayer();
    
    void callbackForDown();
private:
    void playerInit(const char *fileName,int allCount,float sprit);
    //DYNAMIC REPRESENTATION OF FILE NAME FILE FRAME NUMBER SPEED
    void createAnimate(const char *fileName,int allCount,float sprit);
    

    bool isStrong;
    int strongCount;
    int strongTime;
    void strongIng(float soso);
    
};
#endif /* defined(__Holdtail__SWGamePlayer__) */


SWGamePlayer.m

 

 

//
//  SWGamePlayer.cpp
//  Holdtail
//
//  Created by Hand Print on 13-8-21.
//
//

#include "SWGamePlayer.h"
#include "SWGameMap.h"
#include "SWGameWorld.h"
#include "SimpleAudioEngine.h"
#include "SWMenu.h"

using namespace cocos2d;
using namespace CocosDenshion;

//Set up two representations of the hero Elf
static Sprite *flySprite;
static Sprite *runSprite;


//Declare static variables
static SWGamePlayer *SWPL;

SWGamePlayer *SWGamePlayer::sharedPlayer(){
    if(SWPL != NULL){
        return SWPL;
    }
    return  NULL;
}



SWGamePlayer *SWGamePlayer::createPlayer(const char* fileName,int allCount,float sprit){
    SWGamePlayer *player = new SWGamePlayer();
    
    if (player && player->initWithFile("nulls.png")) {
        player->autorelease();
        player->playerInit(fileName,allCount,sprit);
        return player;
    }
    
    CC_SAFE_DELETE(player);
    return NULL;

}

void SWGamePlayer::playerInit(const char *fileName,int allCount,float sprit){
    
    SWPL = this;
    
    Size size = Director::getInstance()->getWinSize();
    
    //The hero joins the gun
    auto spgane = Sprite::create("gang01.png");
    spgane->setPosition(Point(40, -10));
    addChild(spgane);
    
    //Create Animations of Animals
    createAnimate(fileName,allCount,sprit);
    
    //Initialize the hero's position
    this->setPosition(Point(size.width/8, size.height/2));
    
    //Set blood volume
    hp = 1000;
    hpMax = 1000;
    
    ControlSlider* slider = ControlSlider::create("brood.png", "broods.png", "null.png");
    slider->setPosition(Point(250, size.height-40));
    slider->setTag(tag_playerHp);
    /* Set the range of the slider bar */
    slider->setMinimumValue(0);
    slider->setMaximumValue(hpMax);
    /* Set the current value of the slider bar directly */
    slider->setValue(hp);
    //slider->setTouchEnabled(false);
    SWGameWorld::sharedWorld()->addChild(slider);
    
    //Add hero image
    Sprite *hmsprite = Sprite::create("gameicon.png");
    hmsprite->setPosition(Point(50, size.height-40));
    SWGameWorld::sharedWorld()->addChild(hmsprite);
    
    
    //Add game progress bar
    Sprite *timebg = Sprite::create("timelinebg.png");
    timebg->setPosition(Point(670, size.height-35));
    SWGameWorld::sharedWorld()->addChild(timebg);
    
    //Add game to animate strips
    Sprite *timeplay = Sprite::create("timelineyou.png");
    timeplay->setPosition(Point(510, size.height-40));
    SWGameWorld::sharedWorld()->addChild(timeplay);
    
    //Let the animation play
//    ActionInterval* moveToGameOver = MoveBy::create(120, Point(320, 0));
//    CallFunc * funCall =CallFunc::create(timeplay, callfunc_selector(SWGamePlayer::gameGoOver));
//    FiniteTimeAction *seq =Sequence::create(moveToGameOver,funCall,NULL);
//    seq->setTag(tag_player_down);
//    timeplay->runAction(seq);

//    MenuItemImage *SPJN01ITEM = MenuItemImage::create("pausebutton.png", "pausedownbutton.png",this,menu_selector(SWGamePlayer::backMenu));
//    SPJN01ITEM->setPosition(Point(420,280));
//    Menu *menu = Menu::create(SPJN01ITEM,NULL);
//    SWGameWorld::sharedWorld()->addChild(menu);
    
    
    
}

void SWGamePlayer::createAnimate(const char *fileName,int allCount,float sprit){
    
    runSprite = Sprite::create("zhujuerun.png");
    runSprite->setTag(tag_player_run);
    Animation *animation = Animation::create();
    Texture2D *texture = TextureCache::getInstance()->addImage("zhujuerun.png");
    int eachWidth = runSprite->getContentSize().width/8;
    for (int i = 0; i<8; i++) {
        animation->addSpriteFrameWithTexture(texture, Rect(i*eachWidth, 0, eachWidth, this->getContentSize().height));
    }
    animation->setDelayPerUnit(0.1f);//Must be set or it will not play dynamically
    animation->setRestoreOriginalFrame(true);//Whether to go back to the first
    animation->setLoops(-1);//Number of repetitions
    FiniteTimeAction *animaterun = Animate::create(animation);
    runSprite->setPosition(this->getPosition());
    runSprite->runAction(animaterun);
    this->addChild(runSprite);
    
    
    flySprite = Sprite::create("zhujue.png");
    flySprite->setTag(tag_player_fly);
    Animation *animations = Animation::create();
    Texture2D *textures = TextureCache::getInstance()->addImage("zhujue.png");
    int eachWidths = flySprite->getContentSize().width/8;
    for (int i = 0; i<8; i++) {
        animations->addSpriteFrameWithTexture(textures, Rect(i*eachWidths, 0, eachWidths, this->getContentSize().height));
    }
    animations->setDelayPerUnit(0.05f);//Must be set or it will not play dynamically
    animations->setRestoreOriginalFrame(true);//Whether to go back to the first
    animations->setLoops(-1);//Number of repetitions
    FiniteTimeAction *animateruns = Animate::create(animations);
    flySprite->setPosition(this->getPosition());
    flySprite->runAction(animateruns);
    this->addChild(flySprite);
    
    
    runSprite->setOpacity(0);
    flySprite->setOpacity(255);
}


void SWGamePlayer::downHp(float _value){
    //Use this method to detect collisions
    //Get blood volume minus blood volume
    hp = hp-_value;
    //Update blood ICO
    ControlSlider *slider = (ControlSlider *)SWGameWorld::sharedWorld()->getChildByTag(tag_playerHp);
    slider->setValue(hp);
    
    //Determine if the hero's blood has reached zero
    if(0 >= hp){
        Size size = Director::getInstance()->getWinSize();
        LayerColor *layer = LayerColor::create(Color4B(0, 0, 0, 200), size.width, size.height);
        Sprite *sp = Sprite::create("fail_bg.png");
        sp->setPosition(Point(size.width*0.5, size.height*0.5));
        layer->addChild(sp);
        
    }else{
        //Flash effect when the hero is invincible
        isStrong = true;
        strongCount = 0;
        strongTime = 1*30;
        this->schedule(schedule_selector(SWGamePlayer::strongIng));
    }
}

//Invincible Time Processing Function
void SWGamePlayer::strongIng(float soso){
    strongCount++;
    if(strongCount%strongTime == 0){
        this->setVisible(true);
        this->unschedule(schedule_selector(SWGamePlayer::strongIng));
    }else{
        //Flash effect when the hero is invincible
        if(strongCount%3 == 0){
            this->setVisible(false);
        }else{
            this->setVisible(true);
        }
    }
}

void SWGamePlayer::callbackForDown(){
    //Switch animation to walking mode when starting to let the hero fly
    Sprite *run = (Sprite *)this->getChildByTag(tag_player_run);
    run->setOpacity(255);
    Sprite *fly = (Sprite *)this->getChildByTag(tag_player_fly);
    fly->setOpacity(0);
}


 


Then add the hero's configuration to the game world

Of course, there are also minor changes to the game's world class

SWGameWorld.h

 

//
//  SWGameWorld.h
//  Holdtail
//
//  Created by Hand Print on 13-12-02.
//
//

#ifndef __Holdtail__SWGameWorld__
#define __Holdtail__SWGameWorld__

#include <iostream>
#include "cocos2d.h"
#include "cocos-ext.h"

USING_NS_CC;
USING_NS_CC_EXT;
//Define Properties
typedef enum {
    tag_player
}tagWorld;

class SWGameWorld:public cocos2d::Layer{
public:
    static cocos2d::Scene *scene();
    static SWGameWorld *sharedWorld();
    
    void onTouchesBegan(const std::vector<Touch*>& touches, Event  *event);
    void onTouchesMoved(const std::vector<Touch*>& touches, Event  *event);
    void onTouchesEnded(const std::vector<Touch*>& touches, Event  *event);
private:
    virtual bool init();
    CREATE_FUNC(SWGameWorld);
};
#endif /* defined(__Holdtail__SWGameWorld__) */


SWGameWorld.cpp

 

 

//
//  SWGameWorld.cpp
//  Holdtail
//
//  Created by Hand Print on 13-12-02.
//
//

#include "SWGameWorld.h"
#include "cocos2d.h"
#include "SimpleAudioEngine.h"
#include "SWGameMap.h"
#include "SWGamePlayer.h"

using namespace cocos2d;
using namespace CocosDenshion;

//Declare static variables
static SWGameWorld *SWGW;

SWGameWorld *SWGameWorld::sharedWorld(){
    if(SWGW != NULL){
        return SWGW;
    }
    return  NULL;
}


Scene *SWGameWorld::scene(){
    Scene *scene = Scene::create();
    SWGameWorld *layer = SWGameWorld::create();
    scene->addChild(layer);
    
    return scene;
}

//Create Scene
bool SWGameWorld::init(){
    if( !Layer::init()){
        return false;
    }
    SWGW = this;
    
    //Map
    SWGameMap *map = SWGameMap::createMap("cloudbg.png","cloud04.png","cloud03.png","cloud02.png","cloud01.png","treesbg.png");
    addChild(map);
    
    //Create protagonist
    SWGamePlayer *player = SWGamePlayer::createPlayer("zhujuerun.png", 8, 0.05f);
    addChild(player,10,tag_player);
    
    
    setTouchEnabled(true);
	//Set to Single Response
	setTouchMode(Touch::DispatchMode::ALL_AT_ONCE);
    
    auto myListener = EventListenerTouchAllAtOnce::create();
    myListener->onTouchesBegan = CC_CALLBACK_2(SWGameWorld::onTouchesBegan, this);
    myListener->onTouchesMoved = CC_CALLBACK_2(SWGameWorld::onTouchesMoved, this);
    myListener->onTouchesEnded = CC_CALLBACK_2(SWGameWorld::onTouchesEnded, this);
    
    
    return true;
}


void SWGameWorld::onTouchesBegan(const std::vector<Touch*>& touches, Event  *event){
    
    for (int i = 0; i<touches.size(); i++) {
        if (0 == i) {
            SWGameMap::updateLayerHeight(0);
        }
    }
}
void SWGameWorld::onTouchesMoved(const std::vector<Touch*>& touches, Event  *event){
    
}
void SWGameWorld::onTouchesEnded(const std::vector<Touch*>& touches, Event  *event){
    for (int i = 0; i<touches.size(); i++) {
        if (0 == i) {
            SWGameMap::updateLayerHeight(1);
        }
    }
}


Well, the protagonist can move up and down, the principle is to control the background movement, so as to achieve the protagonist's moving effect

 


Packaged Downloads for this stage of the project today - > Airplane Direct


 

Reprinted at: https://www.cnblogs.com/riasky/p/3465140.html

Added by flying_circus on Sat, 27 Jul 2019 20:37:54 +0300