How to Create a tile-based game Cocos2d-x 2.0.4

Source: Internet
Author: User

This article practice from Ray wenderlich's article "How To Make A tile-based game with cocos2d", the article uses cocos2d, I am here to use Cocos2D-x 2.0.4 for learning and porting. This game is about a ninja searching for watermelon in the desert.
In this section, you will learn how to use tile to create a map, how to load the map to the game, how to make the map follow the player's rolling, and how to use the Object layer. The next section describes how to create a collision-able area in a map, how to use the tile attribute, how to create items that can be picked, and how to dynamically modify a map, and how to ensure that ninja does not get rid of it.
 
The procedure is as follows:
1. Create a New Cocos2d-win32 project named "tilegame", 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;

3. Use tiled to create a map. First, download the open-sourceTiled map editorTool. The current version is 0.8.1. We recommend that you use the QT version. On the tiled tool, click "file"> "new file" in the menu bar and fill in the following content in the pop-up dialog box:

Map direction: Normal, 45 degrees. The map size is in tile units. The block size is the actual pixel size of each Tile of the resource. In this article, 32x32 is used. Click "OK ".
4. Add the required tile set to the tool. In the menu bar → "map" → "New Graph block", enter the following content:

Click "Browse" and select"Resources"DirectoryTmw_desert_spacing.pngFile, the "name" content is automatically filled. The block width and height are 32 pixels. The margin is the number of pixels that should be skipped when the current tile block starts to calculate the actual pixel. The width and height are the same. The distance is the pixel distance between two tile blocks, with the same width and height. LookTmw_desert_spacing.pngFile, you can see that each tile block has a black border of 1 pixel, Which is why you need to set the margin and spacing to 1 pixel.

Click "OK ".
5. the tile block is displayed in the "Graph block" window. Now you can start to draw a map. Click the menu bar → "View" → "display grid" to enable the grid reference line. Click "Stamp brush" on the toolbar, click a tile block in the "Block" window, and then click the desired position in the map.

Use the toolbar "fill" to fill the map background into the same tile block, which is a desert background. You can click multiple tile blocks in the "Graph block" window and press Ctrl to select multiple blocks. This allows you to add multiple tile blocks to the map at a time. Make a map and make sure there are at least one pair of buildings on the map, because there is something to be followed for collision. After creating a map, double-click the current layer in the "layers" window.
1 ", rename it to" background ". Click "save" on the toolbar, name it "tilemap. tmx", and save it"Resources"Directory.

6. Add the tile map to the scene. InHelloworldscene. hFile, add the following code:

1
2
Cc_synthesize_retain (cocos2d: cctmxtiledmap *, _ tilemap, tilemap );
Cc_synthesize_retain (cocos2d: cctmxlayer *, _ background, background );

InHelloworldscene. cppFile, add the following constructor:

1
2
3
4
5
Helloworld: helloworld ()
{
_ Tilemap = NULL;
_ Background = NULL;
}

InitializationInitModify the function as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Bool helloworld: Init ()
{
Bool Bret = false;
Do
{
Cc_break_if (! Cclayer: Init ());

This-> settilemap (cctmxtiledmap: Create ("tilemap. tmx "));
This-> setbackground (_ tilemap-> layernamed ("background "));
This-> addchild (_ tilemap,-1 );
Bret = true;
} While (0 );

Return Bret;
}

7. Compile and run the map. You can see the lower left corner of the map, as shown in:

To make it a game, three more things are required: players, player initial points, and moving views to see players.
8. tiled supports two types of layers: tile layer and Object layer. The Object layer allows you to draw rectangles in areas where events may occur on the map. For example, you may need a region where a monster is born, or an area that will crash as soon as it enters. Here we create a place of birth for players. Menu Bar → "layer" → "add object Layer", name it "objects", click "insert object" on the toolbar, select a location on the map, and click it, A gray rectangle is displayed, right-click and select "Object Attributes", and enter "spawnpoint" as the name, as shown in:


Click OK. Save the map.
9. InHelloworldscene. hFile, add the following statement:

1
Cc_synthesize_retain (cocos2d: ccsprite *, _ player, player );

InHelloworldscene. cppIn the constructor, add the following:

1
_ Player = NULL;

InInitThe initialization function is added as follows:

1
2
3
4
5
6
7
8
9
10
11
12
Cctmxobjectgroup * objects = _ tilemap-> objectgroupnamed ("objects ");
Ccassert (objects! = NULL, "objects 'object group not found ");
Ccdictionary * spawnpoint = objects-> objectnamed ("spawnpoint ");
Ccassert (spawnpoint! = NULL, "spawnpoint object not found ");
Int x = spawnpoint-> valueforkey ("X")-> intvalue ();
Int y = spawnpoint-> valueforkey ("Y")-> intvalue ();

This-> setplayer (ccsprite: Create ("player.png "));
_ Player-> setposition (CCP (x, y ));
This-> addchild (_ player );

This-> setviewpointcenter (_ player-> getposition ());

Add a methodSetviewpointcenterThe Code is as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Void helloworld: setviewpointcenter (ccpoint position)
{
Ccsize winsize = ccdirector: shareddirector ()-> getwinsize ();

Int x = max (position. X, winsize. width/2 );
Int y = max (position. Y, winsize. Height/2 );
X = min (x, (_ tilemap-> getmapsize (). Width * _ tilemap-> gettilesize (). width)-winsize. width/2 );
Y = min (Y, (_ tilemap-> getmapsize (). Height * _ tilemap-> gettilesize (). Height)-winsize. Height/2 );
Ccpoint actualposition = CCP (x, y );

Ccpoint centerofview = CCP (winsize. width/2, winsize. Height/2 );
Ccpoint viewpoint = ccpsub (centerofview, actualposition );
This-> setposition (viewpoint );
}

The user uploads any coordinates, but some points do not need to be displayed. For example, we do not want the screen to be removed from the map boundary, and there is just a blank space.

If the camera center is smaller than winsize. width/2 or winsize. Height/2, some views will be outside the screen. Similarly, we need to check the boundary conditions. So far, we have always regarded this function as setting the camera center position. However, this is not what we actually do. What is actually done is to move the entire layer. See:

Imagine that in a huge world, we can see the area from 0 to winsize. Height/width. The center of our field of view is centerofview, and we know where to make the center (actualposition ). So to move the center of our field of view to the Right to actualposition, we only need to move the map down to the left. In this step, the coordinates of actualposition and centerofview are subtracted, and the coordinates of the helloworld layer are set to this result.
10. Compile and run the program. You can see that ninja is on the screen, as shown in:

11. Next, let the ninja move. InHelloworldscene. cppFileInitAdd the following code to the function:

1
This-> settouchenabled (true );

Enable touch, and then reloadRegisterwithtouchdispatcherThe Code is as follows:

1
2
3
4
Void helloworld: registerwithtouchdispatcher (void)
{
Ccdirector: shareddirector ()-> gettouchdispatcher ()-> addtargeteddelegate (this, 0, true );
}

Register the touch event so that the single-touch cctouchbegan and cctouchended will be called. Heavy LoadCctouchbeganThe Code is as follows:

1
2
3
4
Bool helloworld: cctouchbegan (cctouch * ptouch, ccevent * pevent)
{
Return true;
}

If the return value is true, this touch is accepted. AddSetplayerpositionMethod To set the player coordinates. The Code is as follows:

1
2
3
4
Void helloworld: setplayerposition (ccpoint position)
{
_ Player-> setposition (position );
}

Heavy LoadCctouchendedThe 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
Void helloworld: cctouchended (cctouch * ptouch, ccevent * pevent)
{
Ccpoint touchlocation = This-> converttouchtonodespace (ptouch );

Ccpoint playerpos = _ player-> getposition ();
Ccpoint diff = ccpsub (touchlocation, playerpos );
If (ABS (diff. X)> ABS (diff. y ))
{
If (diff. x> 0)
{
Playerpos. x + = _ tilemap-> gettilesize (). width;
}
Else
{
Playerpos. X-= _ tilemap-> gettilesize (). width;
}
}
Else
{
If (diff. Y> 0)
{
Playerpos. Y + = _ tilemap-> gettilesize (). height;
}
Else
{
Playerpos. Y-= _ tilemap-> gettilesize (). height;
}
}

If (playerpos. x <= (_ tilemap-> getmapsize (). Width * _ tilemap-> gettilesize (). width )&&
Playerpos. Y <= (_ tilemap-> getmapsize (). Height * _ tilemap-> gettilesize (). Height )&&
Playerpos. Y> = 0 & playerpos. x> = 0)
{
Setplayerposition (playerpos );
}

Setviewpointcenter (_ player-> getposition ());
}

Calculate the difference between the touch point and the player coordinate to determine the movement direction of the player.
12. Compile and run the program. Click the screen to bring the ninja up, as shown in:

References:
1. How to Make a tile-based game with cocos2d

Http://www.raywenderlich.com/1163/how-to-make-a-tile-based-game-with-cocos2d

2. How to Use cocos2d to create a tile-based game

Http://www.raywenderlich.com/zh-hans/16771/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8cocos2d%E5%88%B6%E4%BD%9C%E4%B8%80%E6%AC%BE%E5%9F%BA%E4%BA%8Etile%E7%9A%84%E6%B8%B8%E6%88%8F

3. How to Use cocos2d to create a tile-Based Map game Tutorial: Part 1

Http://www.cnblogs.com/zilongshanren/archive/2011/04/11/2012852.html

Thank you very much for the above materials. In this example, additional resources are added to the source code.: Http://download.csdn.net/detail/akof1314/4966622
If there is an error in the article, please point it out for correction.

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.