Create a tower defense game Cocos2d-x 2.1.4 (1)

Source: Internet
Author: User

In this article, we will learn how to create a tower guard game. Here, we will learn how to show up a wave of enemies at a set time, move these enemies forward along a specified path, and how to create a turret at a specified position on the map, how to enable the turret to fire the enemy, and how to visually debug the attack range of the route points and turret.

This example is very suitable for beginners. It is helpful for beginners who are familiar with cocos2d. I hope cocos beginners can do it carefully. I have just started to consult the author of the original article several times, success!


1. Create a New Cocos2d-win32 project named TowerDefense, remove the Box2D option, and check the "Simple Audio Engine in Cocos Denshion" option;
2. Download the resources required for the game and place the resources"Resources"Directory;

Resources include source code: http://download.csdn.net/detail/yangshuo528/7426007

3. Add a background image for the scenario. OpenHelloWorldScene. cppFile, modifyInitFunction:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Bool HelloWorld: init ()
{
Bool bRet = false;
Do
{
CC_BREAK_IF (! CCLayer: init ());

This-> setTouchEnabled (true );
CCSize wins = CCDirector: sharedDirector ()-> getWinSize ();
CCSprite * background = CCSprite: create ("Bg.png ");
This-> addChild (background );
Background-> setPosition (ccp (wins. width/2, wins. height/2 ));

BRet = true;
} While (0 );
Return bRet;
}

You can intuitively see the places where players are allowed to place turret images. Compile and run, as shown in:

4. Next, you need to set points along the road to allow players to touch and build turret. To facilitate management, use the. plist file to store the turret placement points so that they can be easily changed.TowersPosition. plistThe resource folder contains some turret positions. View this file and you can see a dictionary array. The dictionary contains only two keys: "x" and "y ". Each dictionary entry represents the x and y coordinates of a turret position. Now you need to read this file and place the base on the map. OpenHelloWorldScene. hFile to add the following variables:

1
Cocos2d: CCArray * towerBases;
Open the HelloWorldScene. cpp file and add the following method:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Void HelloWorld: loadTowerPositions ()
{
CCArray * towerPositions = CCArray: createWithContentsOfFile ("TowersPosition. plist ");
TowerBases = CCArray: createWithCapacity (10 );
TowerBases-> retain ();

CCObject * pObject = NULL;
CCARRAY_FOREACH (towerPositions, pObject)
{
CCDictionary * towerPos = (CCDictionary *) pObject;
CCSprite * towerBase = CCSprite: create ("open_spot.png ");
This-> addChild (towerBase );
TowerBase-> setPosition (ccp (CCString *) towerPos-> objectForKey ("x")-> intValue (),
(CCString *) towerPos-> objectForKey ("y")-> intValue ()));
TowerBases-> addObject (towerBase );
}
}

InInitIn the function, after adding the background image code, add the following code:

1
This-> loadTowerPositions ();
Add the following code to the Destructor:
1
TowerBases-> release ();
Compile and run the task, and you can see the squares on both sides of the road. These are used as the base of the player turret. As shown in:

5. Create a turret. Open the HelloWorldScene. h file and add the following code:
1
CC_SYNTHESIZE_RETAIN (cocos2d: CCArray *, _ towers, Towers );
Add the Tower Class derived from the CCNode class. The Tower. h file code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Ifndef _ TOWER_H __
# Define _ TOWER_H __

# Include "cocos2d. h"
# Include "HelloWorldScene. h"

# Define kTOWER_COST 300

Class Tower: public cocos2d: CCNode
{
Public:
Tower (void );
~ Tower (void );

Static Tower * nodeWithTheGame (HelloWorld * game, cocos2d: CCPoint location );
Bool initWithTheGame (HelloWorld * game, cocos2d: CCPoint location );

Void update (float dt );
Void draw (void );

CC_SYNTHESIZE (HelloWorld *, _ theGame, TheGame );
CC_SYNTHESIZE (cocos2d: CCSprite *, _ mySprite, MySprite );

Private:
Int attackRange;
Int damage;
Float fireRate;
};

# Endif/_ TOWER_H __

OpenTower. cppFile, the Code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# Include "Tower. h"
Using namespace cocos2d;

Tower: Tower (void)
{
}

Tower ::~ Tower (void)
{
}

Tower * Tower: nodeWithTheGame (HelloWorld * game, CCPoint location)
{
Tower * pRet = new Tower ();
If (pRet & pRet-> initWithTheGame (game, location ))
{
Return pRet;
}
Else
{
Delete pRet;
PRet = NULL;
Return NULL;
}
}

Bool Tower: initWithTheGame (HelloWorld * game, CCPoint location)
{
Bool bRet = false;
Do
{
AttackRange = 70;
Damage = 10;
FireRate = 1;

_ MySprite = CCSprite: create ("tower.png ");
This-> addChild (_ mySprite );
_ MySprite-> setPosition (location );
_ TheGame = game;
_ TheGame-> addChild (this );

This-> scheduleUpdate ();

BRet = true;
} While (0 );

Return bRet;
}

Void Tower: update (float dt)
{

}

Void Tower: draw (void)
{
# Ifdef COCOS2D_DEBUG
CcDrawColor4F (255,255,255,255 );
CcDrawCircle (_ mySprite-> getPosition (), attackRange, 360, 30, false );
# Endif
CCNode: draw ();
}

ThisTowerThe class contains several attributes: a Sprite object, which is a visualized manifestation of the turret; a reference to the parent layer for convenient access to the parent layer; there are three variables:

  • AttackRange: the distance between the turret and the enemy.
  • Damage: damage to the enemy caused by the turret.
  • FireRate: The interval at which the turret attacks the enemy again.
With these three variables, you can create turret with different attack attributes, such as Remote Reload attacks that take a long time or a limited range of rapid attacks. Finally, the draw method in the code is used to draw a circle around the turret to show its attack range, which facilitates debugging.


6. Ask the player to add the turret. Open the HelloWorldScene. cpp file and add the following header file declaration:

1
# Include "Tower. h"
Add the following code to the Destructor:
1
_ Towers-> release ();
In the init function, add the following code:
1
2
_ Towers = CCArray: create ();
_ Towers-> retain ();
Add the following two methods. The Code is as follows (do not forget to add the function declaration in HelloWorldScene. h ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Bool HelloWorld: canBuyTower ()
{
Return true;
}

Void HelloWorld: ccTouchesBegan (CCSet * pTouches, CCEvent * pEvent)
{
CCSetIterator iter = pTouches-> begin ();
For (; iter! = PTouches-> end (); iter ++)
{
CCTouch * pTouch = (CCTouch *) (* iter );
CCPoint location = pTouch-> getLocation ();

CCObject * pObject = NULL;
CCARRAY_FOREACH (towerBases, pObject)
{
CCSprite * tb = (CCSprite *) pObject;
If (this-> canBuyTower () & tb-> boundingBox (). containsPoint (location )&&! Tb-> getUserData ())
{
// We will spend our gold later.

Tower * tower = Tower: nodeWithTheGame (this, tb-> getPosition ());
_ Towers-> addObject (tower );
Tb-> setUserData (tower );
}
}
}
}

MethodCcTouchesBeganChecks whether a user traverses the towerBases array when touching any point on the screen and checks whether the touch point is contained on any tower. Before creating a turret, check whether:
① Can a player afford a turret? The canBuyTower method is used to check whether a player has enough gold coins to buy a turret. Assuming that the player has many gold coins, the return value is true.
② Have gamers violated construction rules? If the tb UserData has been set, the base has a turret and cannot be added.
If all checks pass, a new turret is created, placed on the base, and added to the turret array. Compile and run the task. After you touch the base, you can see that the turret is placed, and there are white circles around it to show the attack range, as shown in:


References: 1.How To Make a Tower Defense Game http://www.raywenderlich.com/15730/how-to-make-a-tower-defense-game

How to make a tower defense game: http://blog.csdn.net/akof1314/article/details/8674186

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.