Tiled map in cocos2d-x

Source: Internet
Author: User

The tile map in the cocos2d-x is made through the tiledmap software, the archive format is. tmx format. The procedure of using this software is summarized as follows:

(1) creating a tile Map

1. Open the software, as shown in figure.

2. Create a map (file-> New file)

3. Add a new graph block (Map-> New Graph block)

4. Create a map. In the layers area, right-click to create a new layer and object, and create a map using the tool in the toolbar above.

5. Export. Remember that the format must be tmx.

Description

  • Sometimes, when using a map, an error may be reported that the resource cannot be found. You can use xcode to open the map file and modify the resource path.

After the map is complete, what we need to do next is to read the tmx file and operate the file to achieve the desired effect.

(2) read the contents of the map file

1. cctmxtiledmap class

This class is specifically designed for cocos2d-x to read and parse tmx files. The cctmctiledmap class inherits from the ccnode class. We call static cctmxtiledmap * Create (const char * tmxfile) and static cctmxtiledmap * Create (const char * tmxfile, const char * resourcepath) method to create the cctmxtiledmap object, and then we call addchild (); then we can add the map to the layer.

Cctmxtiledmap has the following features:

  • Each brick element is processed as a Sprite object.
  • Bricks in each map are created only when necessary. objects are created only when developers call the tileat of the cclayer class.
  • Each brick can be rotated, moved, scaled, discolored, and transparent.
  • Developers can delete or add brick elements.
  • The Z axis of the brick can also be modified.
  • Each map object has an anchor. The default value is (0, 0 ).
  • Each layer in tmx becomes a map subnode.
  • Each brick element has a unique flag value.
  • Only XML format is supported, and JSON format is not supported.

Common member functions of cctmxtiledmap:

Obtain and set the map size

L const ccsize & getmapsize (void );

L void setmapsize (const ccsize & var)

Obtain and set the brick size

L const ccsize & getilesize (void );

L void settilesize (cosnt ccsize & var );

Obtain and set the map direction

L const int getmaporientation ();

L void setmaporientation (INT var );

Set and retrieve object arrays

L ccarray * getobjectgroups ();

L void setobjectgroups (ccarray * var );

Obtain and set map attributes

L void setproperties (ccdictionary * var );

L ccdictionary * getproperties (void );

/* Initialization method (commonly used )*/

Static cctmxtiledmap * Create (const char * tmxfile );

/** Obtain the layer in the map by name */

Cctmxlayer * layernamed (const char * layername );

/** Tmxobjectgroup: object group under the same name */

Cctmxobjectgroup * objectgroupnamed (const char * groupname );

/** Get the value of an attribute */

Ccstring * propertynamed (const char * propertyname );

/** Obtain all objects of a graph block in a map (note that a graph block may have multiple objects )*/

Ccdictionary * propertiesforgid (int gid );

2. cctmxlayer (map layer)

// Obtain and set the layer size

Virtual const ccsize & getlayersize (void );

Virtual void setlayersize (const ccsize & var );

// Obtain and set the brick size

Virtual const ccsize & getmaptilesize (void );

Virtual void setmaptilesize (const ccsize & var );

// Obtain and set the attribute of the brick

Virtual cctmxtilesetinfo * gettileset (void );

Virtual void settileset (cctmxtilesetinfo * var );

// Obtain and set the layer attribute dictionary

Virtual ccdictionary * getproperties (void );

Virtual void setproperties (ccdictionary * var );

// Return the brick object at the specified position

Ccsprite * tileat (const ccpoint & tilecoordinate );

// Return the ID of the brick object at the specified position

Unsigned int tilegidat (const ccpoint & tilecoordinate );

// Remove the brick object at the specified position

Void removetileat (const ccpoint & tilecoordinate );

// Obtain and set the layer name

Inline const char * getlayername ();

Inline void setlayername (const char * layername );

3. cctmxobjectgroup class (map object Layer ))

// Obtain the attribute Dictionary of the object Layer

Virtual ccdictionary * getproperties (void );

// Set the attribute Dictionary of the object Layer

Virtual void setproperties (ccdictionary * var );

// Obtain the object in the object Layer

Virtual ccarray * getobjects (void );

// Set the object in the object Layer

Virtual void setobjects (ccarray * var );

// Returns the Object layer name.

Inline const char * getgroupname ();

// Set the Object layer name

Inline void setgroupname (const char * groupname );

// Obtain the value of the specified attribute

Ccstring * propertynamed (const char * propertyname );

// Return the attribute Dictionary Based on the attribute name

Ccdictionary * objectnamed (const char * objectname );

(3) The following is a demo of tile map exercises.

1. The created map is as follows:

2. Code association MAP

1> load the map and read the layer on the map

Bool helloworld: Init () {If (! Cclayer: Init () {return false;} // Add the button to the scene to avoid the button moving along with the map. btnmenu = buttonmenu: Create (); SC-> addchild (btnmenu, 5); // load map _ tilemap = cctmxtiledmap: Create ("mymap. tmx "); addchild (_ tilemap); // Add hero addhero (); // Add layer touch ccdirector: shareddirector ()-> gettouchdispatcher () -> addtargeteddelegate (this, 1, false); // obtain the layer (wall and other obstacles) that cannot be walked in the map _ meta = _ tilemap-> layernamed ("meta "); // hide the walking area _ meta-> setvisible (FAL Se); // get the watermelon layer _ fruit = _ tilemap-> layernamed ("Fruit") on the map; // remember to rehold the array. _ Enemyarray = ccarray: Create (); _ enemyarray-> retain (); // initialize the array containing bullets _ bulletarray = ccarray: Create (); _ bulletarray-> retain (); // Add the enemy addenemy (); // collision detection this-> schedule (schedule_selector (helloworld: updatagame), 0.1); Return true ;}

<2> Add a gamer genie

Void helloworld: addhero () {// obtain the object group cctmxobjectgroup * objectsvalue = _ tilemap-> objectgroupnamed ("hero") in the hero Object layer "); // obtain information about the preset hero object on the map. ccdictionary * spawnpoint = objectsvalue-> objectnamed ("Pa"); _ player = ccsprite: Create ("www.png "); _ player-> setanchorpoint (CCP (0, 0 )); // set the location of the current genie Based on the preset hero location on the graph _ player-> setposition (CCP (spawnpoint-> valueforkey ("X")-> floatvalue (), spawnpoint-> valueforkey ("Y")-> floatvalue (); addchild (_ player );}

<3> Add enemy Genie and character walking actions

Void helloworld: addenemy () {// obtain the object group cctmxobjectgroup * objectsvalue = _ tilemap-> objectgroupnamed ("hero") in the hero Object layer; // Add the enemy, non-fast traversal for (INT I = 0; I <int (objectsvalue-> getobjects ()-> count (); ++ I) {// obtain the corresponding element ccdictionary * element = (ccdictionary *) objectsvalue-> getobjects ()-> objectatindex (I) in the map; // If an enemy object is found, put the genie on the map to display if (element-> valueforkey ("N")-> intvalue () = 1) {// initialize the enemy genie, initialize the initialized enemy object in the map Enemy genie. Ccsprite * enemysprite = ccsprite: Create ("enemy1.png"); float x = element-> valueforkey ("X")-> floatvalue (); float y = element-> valueforkey ("Y")-> floatvalue (); enemysprite-> setposition (CCP (x, y); enemysprite-> setanchorpoint (CCP (0, 0); _ tilemap-> addchild (enemysprite, 4); _ enemyarray-> addobject (enemysprite); // let the enemy move to the hero. Cccallfuncn * func = cccallfuncn: Create (this, callfuncn_selector (helloworld: goon); enemysprite-> runaction (func) ;}} void helloworld :: goon (ccnode * psender) {// obtain the distance between the ccsprite * s = (ccsprite *) psender; // The distance from the X axis, float x = _ player-> getposition (). x-S-> getposition (). x> 0? 10:-10; // float y = _ player-> getposition (). Y-S-> getposition (). Y> 0? 10:-10; ccmoveby * Move = ccmoveby: Create (0.5, CCP (x, y); // recursive call, let the enemy genie move cccallfuncn * func = cccallfuncn:: Create (this, callfuncn_selector (helloworld: goon); s-> runaction (ccsequence: Create (move, func, null ));}

<4> Collision Detection

Void helloworld: updatagame () {// fast traversal of the array ccobject * OBJ = NULL; ccarray_foreach (_ enemyarray, OBJ) {// force type conversion ccsprite * s = static_cast <ccsprite *> (OBJ); If (_ player-> boundingbox (). intersectsrect (S-> boundingbox () {// If a hero collides with the enemy, the game ends and returns to the main scene. Ccdirector: shareddirector ()-> replacescene (mainlayer: Scene () ;}} ccarray_foreach (_ bulletarray, OBJ) {ccsprite * bullet = (ccsprite *) OBJ; ccarray_foreach (_ enemyarray, OBJ) {ccsprite * enemy = (ccsprite *) OBJ; // if a bullet hits an enemy if (bullet-> boundingbox (). intersectsrect (enemy-> boundingbox () {// remove bullets and enemies from the map enemy-> removefromparent (); bullet-> removefromparent (); _ enemyarray-> removeobject (enemy); _ bulletarray-> removeobject (bullet); // after the bullet is removed, it will jump out of the current loop break ;}}}}

<5> get the touch point and operate the person

Bool helloworld: cctouchbegan (cctouch * ptouch, ccevent * pevent) {// obtain the position of the point currently touched. ccpoint point = ptouch-> getlocation (); // convert the OpenGL coordinate system into a node as a standard to locate the node (the leftmost position of the map rather than the position in the lower left corner of the screen) location _ beginpoint = converttonodespace (point); Return true;} void helloworld: cctouchended (cctouch * ptouch, ccevent * pevent) {// obtain the current user's click end point ccpoint point = ptouch-> getlocation (); ccpoint endpoint = converttonodespace (point); If (! (Btnmenu-> isbullet) {// If the start and end points are the same, click it instead of sliding the IF (_ beginpoint. equals (endpoint) {// obtain the original location of the genie ccpoint playerpos = _ player-> getposition (); // obtain the gap between the user's touch point and the original genie point. ccpoint dispos = endpoint-playerpos; // determine whether the offset is vertical or vertical. Drawing is easy to understand // If (ABS (dispos. x)> = ABS (dispos. y) {If (dispos. x> 0) {// offset the width of a graph block at a time. Playerpos. X + = _ tilemap-> gettilesize (). width;} else {playerpos. x-= _ tilemap-> gettilesize (). width ;}} else // up/down {If (dispos. y> 0) {// offset the height of a widget to playerpos. Y + = _ tilemap-> gettilesize (). height;} else {playerpos. y-= _ tilemap-> gettilesize (). height ;}} moveplayer (playerpos); // map moves with the genie setviewpointcenter (_ player-> getposition () ;}} else {// launch darts ccsprite * bullet = ccsprite:: Create ("Projectile. PNG "); bullet-> setposition (_ player-> getposition (); _ tilemap-> addchild (bullet, 4); _ bulletarray-> addobject (bullet ); // The difference between the current hand touch point and the X axis of the hero genie float dx = endpoint. x-_ player-> getposition (). x; // the difference between the current hand touch point and the hero's Y axis float DY = endpoint. y-_ player-> getposition (). y; // coordinate point float lx, ly that the bullet moves toward X and Y; // If (dx> 0) {// draw a picture to see why. Winsize refers to the border of the right screen. Lx = _ tilemap-> gettilesize (). width * _ tilemap-> getmapsize (). width-_ player-> getposition (). x; // ly/Lx = Dy/dx; Ly = Dy/dx * lx;} else {Lx = 0-_ player-> getposition (). x; Ly = Dy/dx * lx;} ccmoveby * Move = ccmoveby: Create (2, CCP (LX, ly )); // execute the function to clear the bullets after the bullets are fired. Cccallfuncn * FF = cccallfuncn: Create (this, callfuncn_selector (helloworld: targetfinish); bullet-> runaction (ccsequence: Create (move, FF, null ));}}

<6> maps move with the movement of Characters

Void helloworld: setviewpointcenter (ccpoint position) {// obtain the size of the current screen. ccsize winsize = ccdirector: shareddirector ()-> getwinsize (); // If the genie is on the left or right side of the screen, the value of X is the current x value of the genie. Otherwise, the value of X is half the screen width. Int x = max (position. x, winsize. width/2); // obtain the size of the entire map. ccsize mapsize = _ tilemap-> getmapsize (); // obtain the width and height ccsize tilesize = _ tilemap-> gettilesize (); cclog ("% lf, % lf", mapsize. width, mapsize. height, tilesize. width, tilesize. height); // mapsize. width is the number of tiles on the X axis of the map. The current value is 30 // mapsize. height is the number of tiles on the Y axis of the map. Currently, it is 10 // re-planning the value of X. X = min (x, mapsize. width * tilesize. width-winsize. width/2); // obtain the ccpoint centerpoint = ccpoint (winsize. width/2, winsize. height/2); // rescheduled location ccpoint actualpoint = ccpoint (x, winsize. height/2); // the final location of the map to be moved to. ccpoint viewpoint = centerpoint-actualpoint; // you can specify the position of the current view. This-> setposition (viewpoint );}

<7> movement control between players and obstacles

Void helloworld: moveplayer (ccpoint p) {// map-> getmapsize (): number of map blocks // map-> gettilesize (): the width and height of each graph block // obtain the target location, that is, the current graph block where int x = P. x/_ tilemap-> gettilesize (). width; // locate the nth part on the X axis. Int y = _ tilemap-> getmapsize (). height-(P. y/_ tilemap-> gettilesize (). height); // locate the position on the nth part of the Y axis. // obtain the current position ccpoint currentpoint = CCP (x, y). // determine whether the position is within the MAP range. If (X! = _ Tilemap-> getmapsize (). Width & Y! = _ Tilemap-> getmapsize (). height) {// whether the target is obtained. the ID of the small block in the graph block is obtained based on the specified vertex. for example, if the obstacle ID is 49 and the watermelon ID is 50. (There are 48 map blocks), (there are 2 meta blocks), and the red is the first 48 + 1 = 49, the second block in green is 48 + 2 = 50; int tilegid = _ meta-> tilegidat (currentpoint); // If the tile has if (tilegid) {// dictionary; obtain the attributes ccdictionary * properties = _ tilemap-> propertiesforgid (tilegid); ccstring * metastr = (ccstring *) properties-> objectforkey ("barrier"); ccstring * fruitstr = (ccstring *) properties-> objectforkey ("watermelon"); // if it encounters an obstacle and is not a watermelon, it will not allow the genie to move if (metastr & Metastr-> compare ("red") = 0) {cclog ("++ \ n "); return;} else if (fruitstr & fruitstr-> compare ("green") = 0) {_ meta-> removetileat (currentpoint); // obtain the current fruit, and remove it from the view. Ccsprite * fruitsprite = _ fruit-> tileat (currentpoint); fruitsprite-> removefromparent ();}} // move the hero to the clicked tile _ player-> setposition (p );}}

<8> remove the genie

// Remove the dart void helloworld: targetfinish (ccnode * psender) {psender-> removefromparent (); _ bulletarray-> removeobject (psender) when the dart reaches the boundary );}

 

Tiled map in cocos2d-x

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.