---
title: "cocos2d-x 45度斜地图的应用"
author: "frank__wang"
date: "2013-09-23T13:57:00Z"
tags: []
slug: "cocos2d-x-45"
draft: false
lastmod: "2013-09-25T19:39:05Z"
id: 1947254
url: "https://frank--wang.iteye.com/blog/1947254"
---

# 原文地址：http://blog.csdn.net/dingxiaowei2013/article/details/11894879

# 前言：

我们在做经典的格斗类的游戏的时候，场景常常用的是45°斜地图来创建的。下面我就来实现一个简单的Demo来展现一下斜地图的使用。

# []()功能实现：

## []()1.倾斜地图的加载；

## []()2.点击地图居中；

## []()3.主角只能在一定的范围内移动；

## []()4.鼠标点击屏幕，主角移动一格，如果连续点击则主句不断的移动；

# []()代码实现：

图层要设置z轴属性，方便可以隐藏主角：

在图层的属性中加上 cc\_vertexz -400

如果前面的图层那就设置为automatic

## []()在AppDelegate添加代码：

**\[plain]**[view plain](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "view plain")[copy](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "copy")[print](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "print")[?](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "?")

1. //深度测试，方便实现遮盖效果
2. CCDirector::sharedDirector()-&gt;setDepthTest(true);
3. //Opengl渲染设置,如果地图有背景图层的话就需要加这句
4. CCDirector::sharedDirector()-&gt;setProjection(kCCDirectorProjection2D);

## []()Player类：

**\[plain]**[view plain](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "view plain")[copy](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "copy")[print](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "print")[?](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "?")

01. #ifndef\_\_\_5tilemap\_\_Player\__
02. #define\_\_\_5tilemap\_\_Player\__
03. #include&lt;iostream&gt;
04. #include"cocos2d.h"
05. usingnamespacecocos2d;
06. classPlayer:publicCCSprite
07. {
08. public:
09. staticPlayer\*create();
10. virtualboolinitPlayer();
11. voidupdateVertextZ(CCPointtilePos,CCTMXTiledMap\*tileMap);
12. };
13. #endif/\*defined(\_\_\_5tilemap\_\_Player\_\_)\*/

**\[plain]**[view plain](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "view plain")[copy](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "copy")[print](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "print")[?](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "?")

01. #include"Player.h"
02. staticPlayer\*s;
03. Player\*Player::create()
04. {
05. s=newPlayer();
06. if(s&&s-&gt;initPlayer()){
07. s-&gt;autorelease();
08. returns;
09. }
10. else
11. {
12. deletes;
13. s=NULL;
14. returnNULL;
15. }
16. }
17. boolPlayer::initPlayer()
18. {
19. if(!CCSprite::initWithFile("ninja.png")){
20. returnfalse;
21. }
22. returntrue;
23. }
24. voidPlayer::updateVertextZ(cocos2d::CCPointtilePos,cocos2d::CCTMXTiledMap\*tileMap)
25. {
26. floatlowestZ=-(tileMap-&gt;getMapSize().width+tileMap-&gt;getMapSize().height);
27. floatcurrentZ=tilePos.x+tilePos.y;
28. this-&gt;setVertexZ(lowestZ+currentZ-1);
29. }

## []()HelloWorld.h:

**\[plain]**[view plain](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "view plain")[copy](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "copy")[print](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "print")[?](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "?")

01. #ifndef\_\_HELLOWORLD\_SCENE\_H\__
02. #define\_\_HELLOWORLD\_SCENE\_H\__
03. #include"cocos2d.h"
04. #include"Player.h"
05. usingnamespacecocos2d;
06. typedefenum{
07. MoveDirectionNone=0,
08. MoveDirectionUpperLeft,
09. MoveDirectionLowerLeft,
10. MoveDirectionUpperRight,
11. MoveDirectionLowerRight,
12. MAX\_MoveDirections
13. }EMoveDirection;
14. classHelloWorld:publiccocos2d::CCLayer
15. {
16. public:
17. //Method'init'incocos2d-xreturnsbool,insteadof'id'incocos2d-iphone(anobjectpointer)
18. virtualboolinit();
19. //there'sno'id'incpp,sowerecommendtoreturntheclassinstancepointer
20. staticcocos2d::CCScene\*scene();
21. CREATE\_FUNC(HelloWorld);
22. virtualvoidccTouchesBegan(CCSet\*pTouches,CCEvent\*pEvent);
23. CCPointlocationFromTouches(CCSet\*touches);
24. Player\*player;
25. CCPointplayableAreaMin,playableAreaMax;
26. //获取瓷砖块的坐标
27. CCPointtilePosFromLocation(CCPointlocation,CCTMXTiledMap\*tilemap);
28. //图层居中
29. voidcenterTileMapOnTileCoord(CCPointtilePos,CCTMXTiledMap\*tileMap);
30. virtualvoidccTouchesEnded(CCSet\*pTouches,CCEvent\*pEvent);
31. CCPointscreenCenter;
32. CCTMXTiledMap\*tileMap;
33. CCRectupperLeft,lowerLeft,upperRight,lowerRight;
34. CCPointmoveOffsets\[MAX\_MoveDirections];
35. EMoveDirectioncurrentMoveDirection;
36. voidupdate(floatdelta);
37. CCPointensureTilePosIsWithinBounds(CCPointtilePos);
38. };
39. #endif//\_\_HELLOWORLD\_SCENE\_H\__

## []()HelloWorldScene.cpp

**\[plain]**[view plain](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "view plain")[copy](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "copy")[print](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "print")[?](http://blog.csdn.net/dingxiaowei2013/article/details/11894879 "?")

001. #include"HelloWorldScene.h"
002. #include"SimpleAudioEngine.h"
003. #include"Player.h"
004. usingnamespacecocos2d;
005. usingnamespaceCocosDenshion;
006. CCScene\*HelloWorld::scene()
007. {
008. //'scene'isanautoreleaseobject
009. CCScene\*scene=CCScene::create();
010. //'layer'isanautoreleaseobject
011. HelloWorld\*layer=HelloWorld::create();
012. //addlayerasachildtoscene
013. scene-&gt;addChild(layer);
014. //returnthescene
015. returnscene;
016. }
017. //on"init"youneedtoinitializeyourinstance
018. boolHelloWorld::init()
019. {
020. //1.superinitfirst
021. if(!CCLayer::init())
022. {
023. returnfalse;
024. }
025. CCSizesize=CCDirector::sharedDirector()-&gt;getWinSize();
026. //添加一个地图
027. CCTMXTiledMap\*tileMap=CCTMXTiledMap::create("huohuo.tmx");
028. //CCTMXTiledMap\*tileMap=CCTMXTiledMap::create("isometric.tmx");
029. //tileMap-&gt;setAnchorPoint(CCPointMake(size.width/2,size.height/2));
030. //tileMap-&gt;setPosition(CCPointMake(size.width/2,size.height/2));
031. CCSizes=tileMap-&gt;getContentSize();
032. CCLog("width:%f",-s.width/2);
033. tileMap-&gt;setPosition(ccp(-s.width/2,0));
034. this-&gt;addChild(tileMap,-1,1);
035. this-&gt;setTouchEnabled(true);
036. this-&gt;tileMap=tileMap;
037. //添加主角精灵
038. player=Player::create();
039. player-&gt;setPosition(CCPointMake(size.width/2,size.height/2));
040. player-&gt;setAnchorPoint(ccp(0.3f,0.1));
041. this-&gt;addChild(player);
042. constintborderSize=10;
043. playableAreaMin=CCPointMake(borderSize,borderSize);
044. playableAreaMax=CCPointMake(tileMap-&gt;getMapSize().width-1-borderSize,tileMap-&gt;getMapSize().height-1-borderSize);
045. screenCenter=CCPointMake(size.width/2,size.height/2);
046. upperLeft=CCRectMake(0,screenCenter.y,screenCenter.x,screenCenter.y);
047. lowerLeft=CCRectMake(0,0,screenCenter.x,screenCenter.y);
048. upperRight=CCRectMake(screenCenter.x,screenCenter.y,screenCenter.x,screenCenter.y);
049. lowerRight=CCRectMake(screenCenter.x,0,screenCenter.x,screenCenter.y);
050. moveOffsets\[MoveDirectionNone]=CCPointZero;
051. moveOffsets\[MoveDirectionUpperLeft]=CCPointMake(-1,0);
052. moveOffsets\[MoveDirectionLowerLeft]=CCPointMake(0,1);
053. moveOffsets\[MoveDirectionUpperRight]=CCPointMake(0,-1);
054. moveOffsets\[MoveDirectionLowerRight]=CCPointMake(1,0);
055. currentMoveDirection=MoveDirectionNone;
056. //通过预约的更新方法来检查角色的移动
057. this-&gt;scheduleUpdate();
058. returntrue;
059. }
060. //返回点击的坐标点
061. CCPointHelloWorld::locationFromTouches(cocos2d::CCSet\*touches)
062. {
063. CCTouch\*touch=(CCTouch\*)touches-&gt;anyObject();
064. returntouch-&gt;getLocation();
065. }
066. voidHelloWorld::ccTouchesBegan(cocos2d::CCSet\*pTouches,cocos2d::CCEvent\*pEvent)
067. {
068. //CCNode\*node=this-&gt;getChildByTag(1);
069. //CCTMXTiledMap\*tileMap=(CCTMXTiledMap\*)node;
070. //CCPointtouchLocation=this-&gt;locationFromTouches(pTouches);
071. //CCPointtilepos=this-&gt;tilePosFromLocation(touchLocation,tileMap);
072. //CCLog("%f,%f",tilepos.x,tilepos.y);
073. //
074. //this-&gt;centerTileMapOnTileCoord(tilepos,tileMap);
075. //
076. //player-&gt;updateVertextZ(tilepos,tileMap);
077. CCTouch\*touch=(CCTouch\*)pTouches-&gt;anyObject();
078. CCPointtouchLocation=touch-&gt;getLocation();
079. if(upperLeft.containsPoint(touchLocation)){
080. currentMoveDirection=MoveDirectionUpperLeft;
081. }
082. elseif(lowerLeft.containsPoint(touchLocation))
083. {
084. currentMoveDirection=MoveDirectionLowerLeft;
085. }
086. elseif(upperRight.containsPoint(touchLocation))
087. {
088. currentMoveDirection=MoveDirectionUpperRight;
089. }
090. elseif(lowerRight.containsPoint(touchLocation))
091. {
092. currentMoveDirection=MoveDirectionLowerRight;
093. }
094. }
095. //获取瓷砖块的坐标
096. CCPointHelloWorld::tilePosFromLocation(cocos2d::CCPointlocation,cocos2d::CCTMXTiledMap\*tilemap)
097. {
098. CCPointpos=ccpSub(location,tilemap-&gt;getPosition());
099. floathalfMapWidth=tilemap-&gt;getMapSize().width\*0.5f;
100. floatmapHeight=tilemap-&gt;getMapSize().height;
101. floattileWidth=tilemap-&gt;getTileSize().width;
102. floattileHeight=tilemap-&gt;getTileSize().height;
103. CCPointtilePasDiv=ccp(pos.x/tileWidth,pos.y/tileHeight);
104. floatinverseTileY=mapHeight-tilePasDiv.y;
105. floatposX=(int)(inverseTileY+tilePasDiv.x-halfMapWidth);
106. floatposY=(int)(inverseTileY-tilePasDiv.x+halfMapWidth);
107. //posX=MAX(0,posX);
108. //posX=MIN(tilemap-&gt;getMapSize().width-1,posX);
109. //posY=MAX(0,posY);
110. //posY=MIN(tilemap-&gt;getMapSize().height-1,posY);
111. posX=MAX(playableAreaMin.x,posX);
112. posX=MIN(playableAreaMax.x,posX);
113. posY=MAX(playableAreaMin.y,posY);
114. posY=MIN(playableAreaMax.y,posY);
115. pos=CCPointMake(posX,posY);
116. returnpos;
117. }
118. //将地图居中
119. voidHelloWorld::centerTileMapOnTileCoord(cocos2d::CCPointtilePos,cocos2d::CCTMXTiledMap\*tileMap)
120. {
121. //获取屏幕大小和屏幕中心点
122. CCSizesize=CCDirector::sharedDirector()-&gt;getWinSize();
123. CCPointscreenCenter=CCPointMake(size.width/2,size.height/2);
124. //获取地板层
125. CCTMXLayer\*layer=tileMap-&gt;layerNamed("Ground");
126. //CCTMXLayer\*layer=tileMap-&gt;layerNamed("GroundLayer1");
127. //仅仅在内部使用；瓷砖的Y坐标减去1
128. tilePos.y-=1;
129. //获取瓷砖块坐标
130. CCPointscrollPosition=layer-&gt;positionAt(tilePos);
131. //考虑到地图移动的情况，我将像素坐标信息乘以-1，从而得到负值
132. scrollPosition=ccpMult(scrollPosition,-1);
133. //为屏幕中央坐标添加位移值
134. scrollPosition=ccpAdd(scrollPosition,screenCenter);
135. CCMoveTo\*move=CCMoveTo::create(.2f,scrollPosition);
136. tileMap-&gt;stopAllActions();
137. tileMap-&gt;runAction(move);
138. }
139. voidHelloWorld::update(floatdelta)
140. {
141. if(tileMap-&gt;numberOfRunningActions()==0){
142. if(currentMoveDirection!=MoveDirectionNone){
143. CCPointtilePos=this-&gt;tilePosFromLocation(screenCenter,tileMap);
144. CCPointoffset=moveOffsets\[currentMoveDirection];
145. tilePos=CCPointMake(tilePos.x+offset.x,tilePos.y+offset.y);
146. tilePos=this-&gt;ensureTilePosIsWithinBounds(tilePos);
147. this-&gt;centerTileMapOnTileCoord(tilePos,tileMap);
148. }
149. }
150. //连续不断的修改角色的vertexz的值
151. CCPointtilePos=this-&gt;tilePosFromLocation(tilePos,tileMap);
152. player-&gt;updateVertextZ(tilePos,tileMap);
153. }
154. CCPointHelloWorld::ensureTilePosIsWithinBounds(CCPointtilePos)
155. {
156. tilePos.x=MAX(playableAreaMin.x,tilePos.x);
157. tilePos.x=MIN(playableAreaMax.x,tilePos.x);
158. tilePos.y=MAX(playableAreaMin.y,tilePos.y);
159. tilePos.y=MIN(playableAreaMax.y,tilePos.y);
160. returntilePos;
161. }
162. voidHelloWorld::ccTouchesEnded(cocos2d::CCSet\*pTouches,cocos2d::CCEvent\*pEvent)
163. {
164. currentMoveDirection=MoveDirectionNone;
165. }

# []()实现效果：

![](http://img.blog.csdn.net/20130922130129953)![](http://img.blog.csdn.net/20130922130115875)

![](http://img.blog.csdn.net/20130922162554609)

# []()源码下载：

[http://download.csdn.net/detail/s10141303/6302839](http://download.csdn.net/detail/s10141303/6302839)