[Cocos2d-x] Horizontal Rolling Screen shooting game ① ---- background Rolling

Source: Internet
Author: User

This article describes how to develop a horizontal scrolling shooting game.
1. Rebuild the background in the code
Create a node ParallaxBackground in the project. The header file is very simple.
/*
* ParallaxBackground. h
*
* Created on: 2012-9-18
* Author: Panda
*/
 
# Ifndef PARALLAXBACKGROUND_H _
# Define PARALLAXBACKGROUND_H _
 
# Include "cocos2d. h"
USING_NS_CC;
 
Class ParallaxBackground: public CCNode {
Public:
ParallaxBackground ();
Virtual ~ ParallaxBackground ();
 
CCSpriteBatchNode * batchnode;
// Number of elves that constitute the background
Int numSprites;
// Movement speed
Float scrollSpeed;
 
Virtual bool init ();
Void update (ccTime time );
 
CREATE_FUNC (ParallaxBackground );
};
 
# Endif/* PARALLAXBACKGROUND_H _*/
Here I have set a reference to the CCSpriteBatchNode node. We will call this node frequently in the code. Calling a node saved in a member variable is faster than calling it using the getNodeByTag method. If you do this in each frame, you can save several CPU processing cycles. Of course, if you need to save dozens or even hundreds of such member variables, it is not worth doing so.
/*
* ParallaxBackground. cpp
*
* Created on: 2012-9-18
* Author: Panda
*/
 
# Include "ParallaxBackground. h"
 
ParallaxBackground: ParallaxBackground (){
// TODO Auto-generated constructor stub
 
}
 
ParallaxBackground ::~ ParallaxBackground (){
// TODO Auto-generated destructor stub
}
 
Bool ParallaxBackground: init (){
Bool bRet = false;
Do {
CCSize size = CCDirector: shareddire()-> getWinSize ();
 
// Obtain the 2d texture of the texture set
CCTexture2D * tt2d = CCTextureCache: sharedTextureCache ()-> addImage (
Game-art.png ");
Batchnode = CCSpriteBatchNode: createWithTexture (tt2d );
This-> addChild (batchnode );
 
NumSprites = 7;
// Add seven different striped images to the batch processing genie object
For (int I = 0; I <numSprites; I ++ ){
CCString * file = CCString: createWithFormat ("bgii.png", I );
 
CCSprite * sprite = CCSprite: createWithSpriteFrameName (
File-> getCString ());

Sprite-> setPosition (CCPointMake (size. width/2, size. height/2 ));
Batchnode-> addChild (sprite, I );
}
ScrollSpeed = 1.0f;
 
This-> scheduleUpdate ();
BRet = true;
} While (0 );
Return bRet;
}
 
Void ParallaxBackground: update (ccTime time ){
CCObject * object = NULL;
CCARRAY_FOREACH (batchnode-> getChildren (), object)
{
CCSprite * sprite = (CCSprite *) object;
CCPoint point = sprite-> getPosition ();
Point. x-= (scrollSpeed + sprite-> getZOrder () * (time * 20 );
Sprite-> setPosition (point );
}
 
}
First, add the texture set game-art.png to CCTextureCache. Actually, I have loaded this texture map set in the GameScene class. Why should I load it again? The reason is that I need to use the CCTexture2D object to generate CCSpriteBatchNode, and adding the same texture to CCTextureCache again is the only way to get the cached texture. This operation will not load the texture again. The Singleton CCTextureCache knows that the texture has been loaded and will directly call the cached version. This operation is very fast. You may wonder why there is no method like getTextureByName to call cached textures. However, this method is not available now.
-----------------------
After CCSpriteBatchNode is created and set, the next step is to load seven independent background images.
// Dynamically generate the file name
CCString * file = CCString: createWithFormat ("bgii.png", I );
// By using the frameName of the genie, I created a common CCSprite and placed it in the center of the screen
CCSprite * sprite = CCSprite: createWithSpriteFrameName (
File-> getCString ());
Sprite-> setPosition (CCPointMake (size. width/2, size. height/2 ));
Next we will explain how to move the background stripe, that is, the code in void ParallaxBackground: update (ccTime time ).
 
The value of the x-axis position of each striped background image is subtracted from the update method of each frame, so that they are moved from the right to the left.
The number of moves depends on the predefined scrollSpeed variable plus the zOrder attribute value of the genie. The value of delta can make the scroll speed independent of the frame rate.
Because delta is only the time between two calls to the update method. For example, if the current frame rate is 60 frames per second, delta is equal to 1/60 seconds, that is, 0.167 seconds, the image with such a value will be very slow, so I will multiply 20 to make the movement faster.
The image that is close to the screen will scroll faster, because the zOrder value is closer to the screen and the larger it is.
 
Because the ParallaxBackground class inherits from CCNode, I only need to add ParallaxBackground TO THE MainScene layer through the following code.
MainScene. cpp Code
Bool MainScene: init (){
Bool bRet = false;
Do {
CCSpriteFrameCache * cache = CCSpriteFrameCache: sharedSpriteFrameCache ();
Cache-> addSpriteFramesWithFile ("game-art.plist ");
 
ParallaxBackground * bg = ParallaxBackground: create ();
This-> addChild (bg,-1 );
 
// This-> scheduleUpdate ();
BRet = true;
 
} While (0 );
Return bRet;
}
 
Factors Affecting the parallax speed
 
In our game, stripes of the same color need to move at the same speed, and the stripes should appear repeatedly to prevent the solid background behind them.
The first change is related to the scroll speed. I used a Vector to store the movement speed of each striped image.
ParallaxBackground header file
/*
* ParallaxBackground. h
*
* Created on: 2012-9-18
* Author: Panda
*/
 
# Ifndef PARALLAXBACKGROUND_H _
# Define PARALLAXBACKGROUND_H _
 
# Include "cocos2d. h"
# Include "vector"
Using namespace std;
 
USING_NS_CC;
 
Class ParallaxBackground: public CCNode {
Public:
ParallaxBackground ();
Virtual ~ ParallaxBackground ();
 
CCSpriteBatchNode * batchnode;
// Number of elves that constitute the background
Int numSprites;
// Movement speed
Float scrollSpeed;
// The movement speed of each striped image]
Vector <float> speedFactors;
 
Virtual bool init ();
Void update (ccTime time); CREATE_FUNC (ParallaxBackground)
;
};
 
# Endif/* PARALLAXBACKGROUND_H _*/
/*
* ParallaxBackground. cpp
*
* Created on: 2012-9-18
* Author: Panda
*/
 
# Include "ParallaxBackground. h"
 
ParallaxBackground: ParallaxBackground (){
// TODO Auto-generated constructor stub
 
}
 
ParallaxBackground ::~ ParallaxBackground (){
// TODO Auto-generated destructor stub
}
 
Bool ParallaxBackground: init (){
Bool bRet = false;
Do {
CCSize size = CCDirector: shareddire()-> getWinSize ();
 
// Obtain the 2d texture of the texture set
CCTexture2D * tt2d = CCTextureCache: sharedTextureCache ()-> addImage (
Game-art.png ");
Batchnode = CCSpriteBatchNode: createWithTexture (tt2d );
This-> addChild (batchnode );
 
NumSprites = 7;
 
SpeedFactors. push_back (0.3f );
SpeedFactors. push_back (0.5f );
SpeedFactors. push_back (0.5f );
SpeedFactors. push_back (0.8f );
SpeedFactors. push_back (0.8f );
SpeedFactors. push_back (1.2f );
SpeedFactors. push_back (1.2f );
 
For (int I = 0; I <numSprites; I ++ ){
CCString * file = CCString: createWithFormat ("bgii.png", I );
CCLog ("file is % s", file-> getCString ());
 
CCSprite * sprite = CCSprite: createWithSpriteFrameName (
File-> getCString ());
 
CCLog ("sprite length: % f, width: % f", sprite-> getContentSize (). width,
Sprite-> getContentSize (). height );
Sprite-> setPosition (CCPointMake (size. width/2, size. height/2 ));
Batchnode-> addChild (sprite, I );
}
 
ScrollSpeed = 1.0f;
 
This-> scheduleUpdate ();
BRet = true;
} While (0 );
Return bRet;
}
 
Void ParallaxBackground: update (ccTime time ){
CCObject * object = NULL;
CCARRAY_FOREACH (batchnode-> getChildren (), object ){
CCSprite * sprite = (CCSprite *) object;
CCPoint point = sprite-> getPosition ();
Point. x-= (scrollSpeed + speedFactors. at (sprite-> getZOrder () * (time * 20 );
Sprite-> setPosition (point );
}
 
}
The code is easy to understand without much explanation.
-------------------------------
Set unlimited scrolling of the background
I added a group of seven background striped images to CCSpriteBatchNodo. Of course, their settings are different from those before.
For (int I = 0; I <numSprites; I ++ ){
CCString * file = CCString: createWithFormat ("bgii.png", I );
CCSprite * sprite = CCSprite: createWithSpriteFrameName (
File-> getCString ());
Sprite-> setAnchorPoint (CCPointMake (0, 0 ));
// Place the new background image on the right of the screen.-1 is used to display a black line at the joint.
Sprite-> setPosition (CCPointMake (size. width-1, 0 ));
// Flip the Sprite in parallel to connect to the first group of images
Sprite-> setFlipX (true );
Batchnode-> addChild (sprite, I );
}
Void ParallaxBackground: update (ccTime time ){
CCSize size = CCDirector: shareddire()-> getWinSize ();
CCObject * object = NULL;
CCARRAY_FOREACH (batchnode-> getChildren (), object ){
CCSprite * sprite = (CCSprite *) object;
CCPoint point = sprite-> getPosition ();
Point. x-= (scrollSpeed + speedFactors. at (sprite-> getZOrder ()))
* (Time * 20 );
If (point. x <-size. width ){
//-2 is used to display the black line at the joint. Why do we need to move two pixels to the left?
// Because the background image that has previously been flipped horizontally has been moved to the left
// One pixel is moved. After you place the background image again, we need to move it two pixels to the left.
// The image must overlap with the left-side background image in 1 pixel.
Point. x + = size. width * 2-2;
}
Sprite-> setPosition (point );
}
 
}
 

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.