Cocos2dx Game Development Series notes 18: game source code analysis

Source: Internet
Author: User

 

Let's take a look at a more common parkour game.

Actually

I think someone used the example of "Lolita run" to change it.

But there must be something new to learn.

This is the best demo we have ever seen. You can run it without having to modify it.

Reporting Environment vs2012 and cocos2dx 2.2 and win8.1 first

I know the new version.

Many people are looking forward to the new version all day,...

1. Create a demo using a python script

2. Click here to download the game source code (thanks to blog.csdn.net/haomengzhu's demo)

3. Copy the Classes and Resources to the new demo.

4 vs open a new demo, import existing items, compile, Once OK

========================================================== ==============

========================================================== ==============================

Main Character: Player

The H file defines the enumeration of player statuses: Mobile arrival death

 

Typedef enum {kPlayerMoving, // The main character is at Mobile kPlayerFalling, // The main character is at the landing of kPlayerDying // The main character is dead} PlayerState;
There are also some basic data:

 

Cycling animation, floating animation, floating time, speed, and so on.

There are also many inline methods and inline Virtual Methods

Introduction to inline reference:

 

The inline keyword is used to define the inline function of a class. The main reason for introducing it is to use it.Replacing the macro definition in expression form in C.
Macro definition in expression form # define ExpressionName (Var1, Var2) (Var1) + (Var2) * (Var1)-(Var2) 1. the reason why C uses this form of macro definition is that C language is a very efficient language. This macro definition is like a function in form and usage, but it is implemented using a Preprocessor, without a series of operations such as parameter pressure stack and code generation, the efficiency is very high. it is similar to a function in form, but when using it, it is simply a simple replacement in the pre-processor symbol table, so itParameter validity cannot be checked., That isC ++ compiler does not support strict type checksIn addition, its return value is notForced conversionIt can be a suitable type for conversion. In this way, its use has a series of risks and limitations. 3. the Class and Class access control are introduced in C ++. In this way, if an operation or expression involves the protection or private member of the class, you cannot use this macro definition (because you cannot place this pointer in a proper position ). 4. The purpose of inline is to replace the macro definition in this expression form. It eliminates the disadvantages of macro definition and inherits the advantages of macro definition. Inline int left () {return this-> getPositionX ()-_ width * 0.5f;} 1. inline functions of classes defined by inline. The code of the functions is put into the symbol table and replaced directly during use (expanded like a macro), without the call overhead and high efficiency. 2. Obviously, the inline function of a class is also a real function. When the compiler calls an inline function, it first checks its parameter type to ensure that the call is correct. Then perform a series of related checks, just like treating any real function. This eliminates its hidden dangers and limitations. 3. inline can be used as a member function of a class. Of course, you can use the protected member and private member of the class. When to use the inline function: First, you can use the inline function completelyReplacing the macro definition in Expression Form. In addition, inline functions generally onlyFunction content is very simpleThis is because the code of the inline function is expanded wherever it is called. If the function is too complex, the consequence of code expansion is likely to be greater than the benefit of efficiency improvement. The most important use of inline functions isClass access functions.

The bones are a little clear, so I will understand them later.

 

In Player. CPP, there are constructor methods and create methods.

The constructor mainly initializes some values.

The create method is mainly used to create the CCSprite object. Some animation and parameter settings are in the init method.

Main Character gliding MethodIt is also a simple playback gliding animation and modification speed.

 

// Set the Drop Action void Player: setFloating (bool value) {if (_ floating = value) return; if (value & _ hasFloated) return; _ floating = value; this-> stopAllActions (); if (value) {_ hasFloated = true; this-> setDisplayFrame (CCSpriteFrameCache: sharedSpriteFrameCache ()-> cached )); this-> runAction (_ floatAnimation); _ vector. y + = PLAYER_JUMP * 0.5f;} else {this-> runAction (_ rideAnimation );}}

 

There is also the void Player: update (float dt) update method:

Here, we will slowly speed up to the maximum speed, and then speed at a constant speed.

Then adjust the speed based on the player status, such as drop, forward, or jump.

Speed-related, easy to understand, but messy.

 

Void Player: update (float dt) {// ACCELERATION to the maximum, and then constant speed if (_ speed + ACCELERATION <= _ maxSpeed) {_ speed + = ACCELERATION ;} else {_ speed = _ maxSpeed;} _ vector. x = _ speed; // CCLog (play state: % d, _ state); switch (_ state) {case kPlayerMoving: _ vector. y-= GRAVITY; if (_ hasFloated) _ hasFloated = false; break; case kPlayerFalling: if (_ floating) {_ vector. y-= FLOATNG_GRAVITY; _ vector. x * = FLOATING_FRICTION;} else {_ vector. y-= GRAVITY; _ vector. x * = AIR_FRICTION; _ floatingTimer = 0;} break; case kPlayerDying: _ vector. y-= GRAVITY; _ vector. x =-_ speed; this-> setPositionX (this-> getPositionX () + _ vector. x); break;} if (_ jumping) {_ state = kPlayerFalling; _ vector. y + = PLAYER_JUMP * 0.25f; if (_ vector. y> PLAYER_JUMP) _ jumping = false;} if (_ vector. y <-TERMINAL_VELOCITY) _ vector. y =-TERMINAL_VELOCITY; _ nextPosition. y = this-> getPositionY () + _ vector. y; if (_ vector. x * _ vector. x <0.01) _ vector. x = 0; if (_ vector. y * _ vector. y <0.01) _ vector. y = 0; if (_ floating) {_ floatingTimer + = dt; if (_ floatingTimer> _ floatingTimerMax) {_ floatingTimer = 0; this-> setFloating (false );}}}

 

========================================================== ====================================

 

Map tiles: Block

The square on the left is a map in the game in a certain order.

Generally, the map editor is used to edit and import data to the game.

I used to take notes before, but I haven't learned it yet.

In Block. h, there are enumeration types and intervals (?) Enumeration.

Defines the width, height, image, and basic animation of the tile, such as moving, hour, scaling, etc.

 

 

CC_SYNTHESIZE (int, _ type, Type); // declare a member Variable _ puffing and the getfunName function. There is no set function. The implementation of the getfunName function must be CC_SYNTHESIZE_READONLY (bool, _ puffing, Puffing); // declare the array of member variables: chimney CC_SYNTHESIZE (CCArray *, _ chimneys, Chimneys );

The bones are not very familiar with this usage,

 

First, let's look at the source code of CC_SYNTHESIZE (int, _ type, Type );

 

#define CC_SYNTHESIZE(varType, varName, funName)protected: varType varName;public: virtual varType get##funName(void) const { return varName; }public: virtual void set##funName(varType var){ varName = var; }
It should be a macro method that automatically generates the set get method.

 

The second CC_SYNTHESIZE_READONLY (bool, _ puffing, Puffing); Method

It should also be a macro Method for Automatically Generating get methods.

This will certainly reduce the amount of code, but for beginners like bones, it is relatively messy and easy to confuse. Be careful when using it.

Then there are several inline methods in the H file.

 

inline virtual int left() {return this->getPositionX();}inline virtual int right() {return this->getPositionX() + _width;}

Let's take a look at the Block. cpp file:

 

 

Block ::~ Block () {// safely release (_ chimneys); CC_SAFE_RELEASE (_ wallTiles); release (_ roofTiles); CC_SAFE_RELEASE (_ puffAnimation); release (_ puffSpawn ); CC_SAFE_RELEASE (_ puffMove); CC_SAFE_RELEASE (_ puffFade); CC_SAFE_RELEASE (_ puffScale );}
In the analysis method of the tile class, the macro definition of this expression is used to look at the source code:

 

 

#define CC_SAFE_DELETE(p)            do { if(p) { delete (p); (p) = 0; } } while(0)#define CC_SAFE_DELETE_ARRAY(p)     do { if(p) { delete[] (p); (p) = 0; } } while(0)#define CC_SAFE_FREE(p)                do { if(p) { free(p); (p) = 0; } } while(0)#define CC_SAFE_RELEASE(p)            do { if(p) { (p)->release(); } } while(0)#define CC_SAFE_RELEASE_NULL(p)        do { if(p) { (p)->release(); (p) = 0; } } while(0)#define CC_SAFE_RETAIN(p)            do { if(p) { (p)->retain(); } } while(0)#define CC_BREAK_IF(cond)            if(cond) break

Use do {...} while (0) in the macro definition of the expression. It seems that there is another lecture: Wait for the bone to study for a while.

 

Similarly, some values are initialized in the constructor, And the CCSprite object Blocl is instantiated in the create method.

Initialize Block configuration information void Block: initBlock ()

Initialize the CCsprite of different types:

 

_tile1 = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName (building_1.png);_tile2 = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName (building_2.png);_tile3 = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName (building_3.png);_tile4 = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName (building_4.png);_roof1 = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName (roof_1.png);_roof2 = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName (roof_2.png);
And put it in two Arrays:

 

 

int i;_wallTiles = CCArray::createWithCapacity(20);_wallTiles->retain();_roofTiles = CCArray::createWithCapacity(5);_roofTiles->retain();CCSprite * tile;for (i = 0; i < 5; i++) {tile = CCSprite::createWithSpriteFrameName(roof_1.png);tile->setAnchorPoint(ccp(0, 1));tile->setPosition(ccp(i * _tileWidth, 0));tile->setVisible(false);this->addChild(tile, kMiddleground, kRoofTile);_roofTiles->addObject(tile);for (int j = 0; j < 4; j++) {tile = CCSprite::createWithSpriteFrameName(building_1.png);tile->setAnchorPoint(ccp(0, 1));tile->setPosition(ccp(i * _tileWidth, -1 * (_tileHeight * 0.47f + j * _tileHeight)));tile->setVisible(false);this->addChild(tile, kBackground, kWallTile);_wallTiles->addObject(tile);}}

Next, initialize the smoke Animation:

 

 

CCAnimation* animation;animation = CCAnimation::create();CCSpriteFrame * frame;for(i = 1; i <= 4; i++) {char szName[100] = {0};sprintf(szName, puff_%i.png, i);frame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(szName);animation->addSpriteFrame(frame);}animation->setDelayPerUnit(0.75f / 4.0f);animation->setRestoreOriginalFrame(false);animation->setLoops(-1);_puffAnimation = CCAnimate::create(animation);_puffAnimation->retain();

Finally, create a smoke Animation:

 

 

void Block::createPuff () {int count = _chimneys->count();CCSprite * chimney;CCSprite * puff;for (int i = 0; i < count; i++) {chimney = (CCSprite * ) _chimneys->objectAtIndex(i);if (chimney->isVisible()) {puff = (CCSprite *) chimney->getChildByTag(_puffIndex);puff->setVisible(true);puff->stopAllActions();puff->setScale(1.0);puff->setOpacity(255);puff->setPosition(ccp(0,0));puff->runAction((CCAction *) _puffAnimation->copy()->autorelease());puff->runAction((CCAction *) _puffMove->copy()->autorelease());//puff->runAction((CCAction *) _puffFade->copy()->autorelease());puff->runAction((CCAction *) _puffScale->copy()->autorelease());}}_puffIndex++;if (_puffIndex == TOTAL_PUFFS) _puffIndex = 0;}

 

There are still map classes and logic Layers

Not complete...

 

------------------- Spacecraft departure --------------------

 

Cocos2dx Game Development Series Notes 17: cocos2dx porting in meow Wang War II

Cocos2dx Game Development Series notes 16: Come to a Demo: cocos2dx version porting in meow Wang war

Cocos2dx Game Development Series notes 15.1: Add a virtual joystick SneakyInput

Cocos2dx Game Development Series notes 14: a horizontal boxing game Demo-lower (let the game run on the mobile phone)

Cocos2dx Game Development Series note 13: a horizontal boxing game Demo-Medium

Cocos2dx Game Development Series Note 12: a horizontal boxing game Demo-on

Cocos2dx Game Development Series note 11

 

Cocos2dx Game Development Series notes 10: Exploring the legend of war

Cocos2dx Game Development Series notes 9: Running legend of war on android phones and solving the problem of adaptive resolution

Cocos2dx Game Development Series notes 8: Start a shooting game named "legend of war "//

Cocos2dx Game Development Series notes 7: A simple and cool-running game "Lori run" for digestion (download link)

Cocos2dx Game Development Series Note 6: how to run the example of "Lori run" on vs and mobile phones

Cocos2dx Game Development Series notes 5: Continue to polish the ninja darts ghost

Cocos2dx Game Development Series notes 4: how to add a new Scene class?

Cocos2dx Game Development Series notes 3: A test with a knife-> a Demo of a ninja darts ghost

Cocos2dx Game Development Series NOTE 2: What is in the demo of a newly created cocos2dx

Cocos2dx Game Development Series Notes 1: a brand new start, cocos2dx2.2 + ndkr9 + Cygwin + vs2012 Game Development Environment Construction

------------------ Ship arrival --------------------

 

Finally, let's look at the zhezhe with his side (the low-key zhezhe on the right)

Zhe, the famous YIYI, the craftsman, the artistic fan, the craftsman, the founder of YiYi Miao she, has his own ideas.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.