cocos2dx A* + tiledMap(改良升级)

前端之家收集整理的这篇文章主要介绍了cocos2dx A* + tiledMap(改良升级)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

此次在之前那篇cocos2dx A* + tiledMap文章中新加了些功能并且调整了结构

拥有的功能:

能避开障碍物,搜寻最优路径

优化了行走的路径,使之平滑行走(之前的是瓦片级的,现在是像素级的,#define PRECISE_SEARCH_PATH 开启精确的路径行走)

添加了人物根据位置会被物体遮住或遮住物体的功能

添加了点击路面,到达该点. 点击物体,可以到达该物体的功能

添加了捡拾物体功能

添加了坐椅子功能

添加了人物的骨骼动画(行走和站立)

PathSearchInfo 搜索路径引擎

Player 玩家类

PathSprite 瓦片精灵类

Paddle物体类(桌子,椅子等)

MathLogic 数学逻辑类



  1. #pragma once
  2. #include "StaticValue.h"
  3. #include "PathSprite.h"
  4. #include "MathLogic.h"
  5. #include "cocos2d.h"
  6. #include <functional>
  7. #include "paddle.h"
  8. USING_NS_CC;
  9. class PathSearchInfo:public CCNode//寻路类(主要负责寻路的参数和逻辑)
  10. {
  11. public:
  12. PathSearchInfo(CCTMXTiledMap* tiledMap);
  13.  
  14. private:
  15. int m_playerMoveStep;//人物当前的行程的索引
  16. std::function<void(CCPoint)> m_moveDone;//移动结束回调
  17. bool m_isSetMoveDoneCallback;
  18.  
  19. std::function<void(vector<PathSprite*>)> m_drawPath;//画线回调 调试用
  20. bool m_isSetDrawPathCallback;
  21.  
  22. std::function<void(CCPoint point,Paddle* selectObj)> m_selectObj;//选中物体回调
  23. bool m_isSetSelectObjCallback;
  24.  
  25. CCTMXTiledMap* m_map;//地图
  26. CCTMXLayer* m_road;//道路
  27. CCSize m_mapSize;//地图大小
  28. CCSize m_tileSize;//地图的块大小
  29. vector<PathSprite*> m_openList;//开放列表(里面存放相邻节点)
  30. PathSprite* m_inspectArray[MAP_WIDTH][MAP_HEIGHT];//全部需要检测的点
  31. vector<PathSprite*> m_pathList;//路径列表
  32. vector<PathSprite*> m_haveInspectList;//检测过的列表
  33. PathSprite* m_moveObj;//移动的物体
  34. bool m_enableMove;//是否能移动
  35. bool m_isMoving;//是否正在移动
  36. public:
  37. CCTMXTiledMap* getMap()
  38. {
  39. return m_map;
  40. }
  41. void setEnableMove(bool isEnable)
  42. {
  43. m_enableMove = isEnable;
  44. }
  45.  
  46. bool getEnableMove()
  47. {
  48. return m_enableMove;
  49. }
  50.  
  51. bool getIsMoving()
  52. {
  53. return m_isMoving;
  54. }
  55. void setMoveDoneCallback(function<void(CCPoint)>& pFunc);//设置回调
  56.  
  57. void setDrawPathCallback(function<void(vector<PathSprite*>)>& pFunc);//设置回调
  58. void setSelectCallback(function<void(CCPoint point,Paddle* selectObj)> &pFunc);//设置回调
  59.  
  60. void initMapObject(const char* layerName,const char* objName);////初始化地图里的物体(设置深度,设置物体回调函数)
  61.  
  62. CCPoint getMapPositionByWorldPosition(CCPoint point);//根据世界坐标得到地图坐标
  63.  
  64. CCPoint getWorldPositionByMapPosition(CCPoint point);//根据地图坐标得到世界坐标
  65.  
  66. void pathFunction( CCPoint point,PathSprite* obj );//计算路径函数
  67.  
  68. private:
  69. void calculatePath();//计算路径
  70. float calculateTwoObjDistance(PathSprite* obj1,PathSprite* obj2);//计算两个物体间的距离
  71.  
  72. void inspectTheAdjacentNodes(PathSprite* node,PathSprite* adjacent,PathSprite* endNode);//把相邻的节点放入开放节点中
  73. PathSprite* getMinPathFormOpenList();//从开放节点中获取F值最小值的点
  74. PathSprite* getObjFromInspectArray(int x,int y);//根据横纵坐标从检测数组中获取
  75. bool removeObjFromOpenList( PathSprite* sprite);//从开放列表中移除对象
  76. void resetInspectArray();//重置检测列表
  77. bool detectWhetherCanPassBetweenTwoPoints(CCPoint p1,CCPoint p2);//检测2个位置中是否有障碍物
  78. void resetObjPosition();//重置玩家位置
  79. void clearPath();//清除路径
  80.  
  81. void moveObj();//移动实现函数
  82. };

  1. #include "PathSearchInfo.h"
  2.  
  3.  
  4. PathSearchInfo::PathSearchInfo( CCTMXTiledMap* tiledMap )
  5. {
  6. memset(m_inspectArray,NULL,MAP_WIDTH*MAP_HEIGHT*sizeof(PathSprite*));
  7. m_isSetMoveDoneCallback = false;
  8. m_isSetDrawPathCallback = false;
  9. m_isSetSelectObjCallback = false;
  10. m_enableMove = true;
  11.  
  12. m_map = tiledMap;
  13. m_mapSize = m_map->getMapSize();//获取地图的尺寸 地图单位
  14. m_tileSize = m_map->getTileSize();//获取瓦片的尺寸 世界单位
  15. m_road = m_map->layerNamed("road");//行走路径的地图
  16.  
  17. for (int j = 0; j < m_mapSize.height; j++) {
  18. for (int i = 0; i < m_mapSize.width; i++) {
  19. CCSprite* _sp = m_road->tileAt(CCPoint(i,j));
  20. if (_sp) {
  21. PathSprite* _pathSprite = new PathSprite(_sp);
  22. _pathSprite->m_x = i;
  23. _pathSprite->m_y = j;
  24.  
  25. m_inspectArray[i][j] = _pathSprite;//把地图中所有的点一一对应放入检测列表中
  26. }
  27. }
  28. }
  29. }
  30.  
  31. void PathSearchInfo::setMoveDoneCallback( function<void(CCPoint)>& pFunc )
  32. {
  33. m_moveDone = pFunc;
  34. m_isSetMoveDoneCallback = true;
  35. }
  36.  
  37. void PathSearchInfo::setDrawPathCallback( function<void(vector<PathSprite*>)>& pFunc )
  38. {
  39. m_drawPath = pFunc;
  40. m_isSetDrawPathCallback = true;
  41. }
  42.  
  43. void PathSearchInfo::setSelectCallback( function<void(CCPoint point,Paddle* selectObj)> &pFunc )
  44. {
  45. m_selectObj = pFunc;
  46. m_isSetSelectObjCallback = true;
  47. }
  48.  
  49. void PathSearchInfo::initMapObject( const char* layerName,const char* objName )
  50. {
  51. //图片
  52. CCTMXLayer* _layer = m_map->layerNamed(layerName);
  53. if (!_layer)
  54. {
  55. return;
  56. }
  57. //对象层
  58. CCTMXObjectGroup* pipeGroup = m_map->objectGroupNamed(objName);
  59. if (!pipeGroup)
  60. {
  61. return;
  62. }
  63. //得到所有的对象
  64. CCArray* _array = pipeGroup->getObjects();
  65. CCObject *_obj;
  66. CCARRAY_FOREACH(_array,_obj )
  67. {
  68. //得一个
  69. CCDictionary* _dictionary = (CCDictionary*)_obj;
  70.  
  71. //得到属性
  72. float _x = ((CCString*)_dictionary->objectForKey("x"))->floatValue();//世界单位
  73. float _y= ((CCString*)_dictionary->objectForKey("y"))->floatValue();
  74. float _widht = ((CCString*)_dictionary->objectForKey("width"))->floatValue();//世界单位
  75. float _height = ((CCString*)_dictionary->objectForKey("height"))->floatValue();
  76.  
  77. CCString* _terminalX = ((CCString*)_dictionary->objectForKey("terminalX"));//终点x坐标
  78. CCString* _terminalY = ((CCString*)_dictionary->objectForKey("terminalY"));//终点y坐标
  79. CCString* _type = ((CCString*)_dictionary->objectForKey("type"));//物体类型
  80. CCString* _enableSit = ((CCString*)_dictionary->objectForKey("enableSit"));//是否能坐下
  81. CCString* _enableTouch =(( CCString*)_dictionary->objectForKey("enableTouch"));//是否能触摸
  82. CCString* _enablePickUp =(( CCString*)_dictionary->objectForKey("enablePickUp"));//是否能触摸
  83.  
  84. Paddle* _parent = Paddle::paddleWithContentSize(CCSize(_widht,_height));//创建一个物体类
  85.  
  86. //设置物体属性
  87. if (_terminalX && _terminalY)
  88. {
  89. _parent->m_terminal = CCPoint( _terminalX->floatValue(),_terminalY->floatValue());
  90. if (m_isSetSelectObjCallback)
  91. {
  92. _parent->m_selectCallback =m_selectObj;
  93. }
  94.  
  95. }
  96. else
  97. {
  98. _parent->m_terminal = CCPoint(-1,-1);
  99. }
  100. _parent->m_type = _type? (OBJTYPE)_type->intValue():NONE_TYPE;
  101. _parent->m_enableSit = _enableSit? _enableSit->boolValue():false;
  102. _parent->m_enableTouch = _enableTouch?_enableTouch->boolValue():false;
  103. if (_enablePickUp)
  104. {
  105. _parent->m_enablePickUp = _enablePickUp->boolValue();
  106. _parent->m_selectCallback =m_selectObj;
  107. }
  108. else
  109. {
  110. _parent->m_enablePickUp =false;
  111. }
  112. //设置物体位置
  113. CCPoint _offset = CCPoint(_x,_y );//偏移量
  114. _parent->setPosition(_offset);
  115. _parent->setAnchorPoint(CCPoint(0,0));
  116.  
  117. for (int i = 0; i < _widht/m_tileSize.width; i++)
  118. {
  119. for (int j = 0; j < _height/m_tileSize.height; j++)
  120. {
  121. CCSprite* _Sprite = _layer->tileAt(CCPoint(_x/m_tileSize.width+i,m_mapSize.height-1-_y/m_tileSize.height-j));
  122. if (_Sprite)
  123. {
  124.  
  125. _Sprite->retain();
  126. _Sprite->removeFromParent();
  127. _Sprite->setPosition(_Sprite->getPosition()-_offset);
  128. _parent->addChild(_Sprite);
  129. _Sprite->release();
  130.  
  131. #if 0//测试该物体
  132. CCMoveBy* action = CCMoveBy::create(1,CCPoint(0,50));
  133. CCMoveBy* actionR = CCMoveBy::create(1,-50));
  134. CCSequence* seq = CCSequence::create(action,actionR,NULL);
  135. _Sprite->runAction(CCRepeatForever::create(seq));
  136. #endif
  137.  
  138. }
  139.  
  140. }
  141. }
  142.  
  143. //设置对象深度
  144. if (_parent->m_enablePickUp)
  145. {
  146. m_map->addChild(_parent,BASE_ZODER - getWorldPositionByMapPosition(m_mapSize).y );
  147. }
  148. else
  149. {
  150. m_map->addChild(_parent,BASE_ZODER - _y );
  151. }
  152.  
  153. }
  154. }
  155.  
  156. void PathSearchInfo::pathFunction( CCPoint point,PathSprite* obj )
  157. {
  158. if (!m_enableMove)
  159. {
  160. return;
  161. }
  162. if (point.x <0 || point.y<0)
  163. {
  164. return;
  165. }
  166. // if (m_moveDone())//判断是否到达目的地
  167. // {
  168. // return;
  169. // }
  170. //m_moveDone();//判断是否到达目的地
  171. m_moveObj = obj;
  172. resetObjPosition();
  173. clearPath();
  174.  
  175. PathSprite*_sp = m_inspectArray[(int)point.x][(int)(point.y)];
  176. if (_sp) {
  177.  
  178. //获取触摸点,设置为终点
  179. obj->m_endX = _sp->m_x;
  180. obj->m_endY = _sp->m_y;
  181. //计算路径
  182. calculatePath();
  183.  
  184. resetInspectArray();
  185. //移动物体
  186. moveObj();
  187.  
  188. //绘制路径
  189. if (m_isSetDrawPathCallback)
  190. {
  191. m_drawPath(m_pathList);
  192. }
  193. }
  194.  
  195. }
  196.  
  197. void PathSearchInfo::calculatePath()
  198. {
  199. #ifdef PRECISE_SEARCH_PATH
  200. //得到开始点的节点
  201. PathSprite* _endNode= m_inspectArray[m_moveObj->m_startX][m_moveObj->m_startY];
  202. //得到结束点的节点
  203. PathSprite* _startNode = m_inspectArray[m_moveObj->m_endX][m_moveObj->m_endY];
  204.  
  205. //因为是开始点 把到起始点的距离设为0,F值也为0
  206. _startNode->m_costToSource = 0;
  207. _startNode->m_FValue = 0;
  208.  
  209. //把已经检测过的点从检测列表中删除
  210. m_inspectArray[m_moveObj->m_endX][m_moveObj->m_endY] = NULL;
  211. //把该点放入已经检测过点的列表中
  212. m_haveInspectList.push_back(_startNode);
  213. //然后加入开放列表
  214. m_openList.push_back(_startNode);
  215.  
  216. PathSprite* _node = NULL;
  217. while (true)
  218. {
  219. //得到离起始点最近的点(如果是第一次执行,得到的是起点)
  220. _node = getMinPathFormOpenList();
  221. if (!_node)
  222. {
  223. //找不到路径
  224. break;
  225. }
  226. //把计算过的点从开放列表中删除
  227. removeObjFromOpenList( _node);
  228. int _x = _node->m_x;
  229. int _y = _node->m_y;
  230.  
  231. //
  232. if (_x ==m_moveObj->m_startX && _y == m_moveObj->m_startY)
  233. {
  234. break;
  235. }
  236.  
  237. //检测8个方向的相邻节点是否可以放入开放列表中
  238.  
  239.  
  240. PathSprite* _adjacent = NULL;
  241.  
  242.  
  243.  
  244.  
  245. _adjacent = getObjFromInspectArray( _x +1,_y);
  246. inspectTheAdjacentNodes(_node,_adjacent,_endNode);
  247.  
  248. _adjacent = getObjFromInspectArray( _x,_y -1);
  249. inspectTheAdjacentNodes(_node,_endNode);
  250.  
  251. _adjacent = getObjFromInspectArray( _x -1,_y+1);
  252. inspectTheAdjacentNodes(_node,_endNode);
  253.  
  254.  
  255. _adjacent = getObjFromInspectArray( _x + 1,_y + 1);
  256. inspectTheAdjacentNodes(_node,_endNode);
  257.  
  258. _adjacent = getObjFromInspectArray( _x +1,_y-1);
  259. inspectTheAdjacentNodes(_node,_y - 1);
  260. inspectTheAdjacentNodes(_node,_endNode);
  261.  
  262.  
  263. }
  264.  
  265. while (_node)
  266. {
  267. //把路径点加入到路径列表中
  268. //m_pathList.insert(m_pathList.begin(),_node);
  269. m_pathList.push_back(_node);
  270. _node = _node->m_parent;
  271. }
  272. #else
  273.  
  274. //得到开始点的节点
  275. PathSprite* _startNode = m_inspectArray[m_moveObj->m_startX][m_moveObj->m_startY];
  276. //得到结束点的节点
  277. PathSprite* _endNode = m_inspectArray[m_moveObj->m_endX][m_moveObj->m_endY];
  278.  
  279. //因为是开始点 把到起始点的距离设为0,F值也为0
  280. _startNode->m_costToSource = 0;
  281. _startNode->m_FValue = 0;
  282.  
  283. //把已经检测过的点从检测列表中删除
  284. m_inspectArray[m_moveObj->m_startX][m_moveObj->m_startY] = NULL;
  285. //把该点放入已经检测过点的列表中
  286. m_haveInspectList.push_back(_startNode);
  287. //然后加入开放列表
  288. m_openList.push_back(_startNode);
  289.  
  290. PathSprite* _node = NULL;
  291. while (true)
  292. {
  293. //得到离起始点最近的点(如果是第一次执行,得到的是起点)
  294. _node = getMinPathFormOpenList();
  295. if (!_node)
  296. {
  297. //找不到路径
  298. break;
  299. }
  300. //把计算过的点从开放列表中删除
  301. removeObjFromOpenList( _node);
  302. int _x = _node->m_x;
  303. int _y = _node->m_y;
  304.  
  305. //
  306. if (_x ==m_moveObj->m_endX && _y == m_moveObj->m_endY)
  307. {
  308. break;
  309. }
  310.  
  311. //检测8个方向的相邻节点是否可以放入开放列表中
  312.  
  313.  
  314. PathSprite* _adjacent = NULL;
  315.  
  316.  
  317.  
  318.  
  319. _adjacent = getObjFromInspectArray( _x +1,_endNode);
  320.  
  321.  
  322. }
  323.  
  324. while (_node)
  325. {
  326. //把路径点加入到路径列表中
  327. m_pathList.insert(m_pathList.begin(),_node);
  328. //m_pathList.push_back(_node);
  329. _node = _node->m_parent;
  330. }
  331. #endif // PRECISE_SEARCH_PATH
  332.  
  333.  
  334. }
  335.  
  336. float PathSearchInfo::calculateTwoObjDistance( PathSprite* obj1,PathSprite* obj2 )
  337. {
  338.  
  339. float _x = abs(obj2->m_x - obj1->m_x);
  340. float _y = abs(obj2->m_y - obj1->m_y);
  341.  
  342. return _x + _y;
  343. }
  344.  
  345. void PathSearchInfo::inspectTheAdjacentNodes( PathSprite* node,PathSprite* endNode )
  346. {
  347. if (adjacent)
  348. {
  349. float _x = abs(endNode->m_x - adjacent->m_x);
  350. float _y = abs(endNode->m_y - adjacent->m_y);
  351.  
  352. float F,G,H1,H2,H3;
  353. adjacent->m_costToSource = node->m_costToSource + calculateTwoObjDistance(node,adjacent);//获得累计的路程
  354. G = adjacent->m_costToSource;
  355.  
  356. //三种算法,感觉H2不错
  357. H1 = _x + _y;
  358. H2 = hypot(_x,_y);
  359. H3 = max(_x,_y);
  360.  
  361. #if 1 //A*算法 = Dijkstra算法 + 最佳优先搜索
  362. F = G + H1;
  363. #endif
  364. #if 0//Dijkstra算法
  365. F = G;
  366. #endif
  367. #if 0//最佳优先搜索
  368. F = H2;
  369. #endif
  370. adjacent->m_FValue = F;
  371.  
  372. adjacent->m_parent = node;//设置父节点
  373. adjacent->m_sprite->setColor(ccORANGE);//搜寻过的节点设为橘色(测试用)
  374. m_haveInspectList.push_back(adjacent);
  375. node->m_child = adjacent;//设置子节点
  376.  
  377. PathSearchInfo::m_inspectArray[adjacent->m_x][adjacent->m_y] = NULL;//把检测过的点从检测列表中删除
  378. PathSearchInfo::m_openList.push_back(adjacent);//加入开放列表
  379. }
  380. }
  381.  
  382. PathSprite* PathSearchInfo::getMinPathFormOpenList()
  383. {
  384. if (m_openList.size()>0) {
  385. PathSprite* _sp =* m_openList.begin();
  386. for (vector<PathSprite*>::iterator iter = m_openList.begin(); iter != m_openList.end(); iter++)
  387. {
  388. if ((*iter)->m_FValue < _sp->m_FValue)
  389. {
  390. _sp = *iter;
  391. }
  392. }
  393. return _sp;
  394. }
  395. else
  396. {
  397. return NULL;
  398. }
  399.  
  400. }
  401.  
  402. PathSprite* PathSearchInfo::getObjFromInspectArray( int x,int y )
  403. {
  404. if (x >=0 && y >=0 && x < m_mapSize.width && y < m_mapSize.height) {
  405. return m_inspectArray[x][y];
  406. }
  407. return NULL;
  408. }
  409.  
  410. bool PathSearchInfo::removeObjFromOpenList( PathSprite* sprite )
  411. {
  412. if (!sprite) {
  413. return false;
  414. }
  415. for (vector<PathSprite*>::iterator iter = m_openList.begin(); iter != m_openList.end(); iter++)
  416. {
  417. if (*iter == sprite)
  418. {
  419. m_openList.erase(iter);
  420. return true;
  421. }
  422. }
  423. return false;
  424.  
  425. }
  426.  
  427. cocos2d::CCPoint PathSearchInfo::getMapPositionByWorldPosition( CCPoint point )
  428. {
  429. return CCPoint((int)(point.x/PathSearchInfo::m_tileSize.width),(int)(PathSearchInfo::m_mapSize.height - point.y/PathSearchInfo::m_tileSize.height) );
  430. }
  431.  
  432. cocos2d::CCPoint PathSearchInfo::getWorldPositionByMapPosition( CCPoint point )
  433. {
  434. return CCPoint(PathSearchInfo::m_tileSize.width * point.x,(PathSearchInfo::m_mapSize.height + point.y)*PathSearchInfo::m_tileSize.height);
  435. }
  436.  
  437. void PathSearchInfo::resetInspectArray()
  438. {
  439. for (vector<PathSprite*>::iterator iter = m_haveInspectList.begin(); iter != m_haveInspectList.end(); iter++)
  440. {
  441. //(*iter)->m_sprite->setColor(ccWHITE);
  442. (*iter)->m_costToSource = 0;
  443. (*iter)->m_FValue = 0;
  444. (*iter)->m_parent = NULL;
  445. (*iter)->m_child = NULL;
  446.  
  447. m_inspectArray[(*iter)->m_x][(*iter)->m_y] = (*iter);
  448. }
  449. }
  450.  
  451. bool PathSearchInfo::detectWhetherCanPassBetweenTwoPoints( CCPoint p1,CCPoint p2 )
  452. {
  453. float _maxX = p1.x>p2.x?p1.x:p2.x;
  454. float _maxY = p1.y>p2.y?p1.y:p2.y;
  455. float _minX = p1.x<p2.x?p1.x:p2.x;
  456. float _minY = p1.y<p2.y?p1.y:p2.y;
  457.  
  458. if (p1.x == p2.x)
  459. {
  460. if (_maxY - _minY >1)
  461. {
  462. return false;
  463. }
  464. float _x = p1.x;
  465. for (int _y = _minY; _y <=_maxY; _y++)
  466. {
  467. PathSprite*_sp = m_inspectArray[(int)_x][(int)(_y)];
  468. if (!_sp)
  469. {
  470. return false;
  471. }
  472. }
  473.  
  474. }
  475. else if (p1.y == p2.y)
  476. {
  477. if (_maxX - _minX > 1)
  478. {
  479. return false;
  480. }
  481. float _y = p1.y;
  482. for (int _x = _minX; _x <=_maxX; _x++ )
  483. {
  484. PathSprite*_sp = m_inspectArray[(int)_x][(int)(_y)];
  485. if (!_sp)
  486. {
  487. return false;
  488. }
  489. }
  490. }
  491. else
  492. {
  493. for (int _y = _minY; _y <= _maxY; _y++)
  494. {
  495. for (int _x = _minX; _x <= _maxX; _x++)
  496. {
  497. float _length = MathLogic::linearEquationWithOneUnknown_solveShortLenghtrequiredPoint(p1,p2,CCPoint(_x,_y));
  498. float _maxLength = MathLogic::calculateLengthrequiredTwoPoint(CCPoint(0,0),CCPoint(0.5,0.5));
  499. if (_length < _maxLength)
  500. {
  501. PathSprite*_sp = m_inspectArray[(int)_x][(int)(_y)];
  502. if (!_sp)
  503. {
  504. return false;
  505. }
  506. }
  507.  
  508. }
  509. }
  510. }
  511.  
  512. return true;
  513. }
  514.  
  515. void PathSearchInfo::resetObjPosition( )
  516. {
  517. #ifdef PRECISE_SEARCH_PATH
  518.  
  519. CCPoint _point = getMapPositionByWorldPosition(m_moveObj->m_sprite->getPosition());
  520. CCSprite* _sp = m_road->tileAt(_point);
  521.  
  522. if (_sp)
  523. {
  524. m_moveObj->m_x = _point.x;
  525. m_moveObj->m_y = _point.y;
  526. }
  527. else
  528. {
  529. CCSprite* _up = m_road->tileAt(_point + CCPoint(0,-1));
  530. if (_up)
  531. {
  532. m_moveObj->m_x = _point.x;
  533. m_moveObj->m_y = _point.y - 1;
  534. return;
  535. }
  536. CCSprite* _down = m_road->tileAt(_point + CCPoint(0,1));
  537. if (_down)
  538. {
  539. m_moveObj->m_x = _point.x;
  540. m_moveObj->m_y = _point.y +1;
  541. return;
  542. }
  543. CCSprite* _left = m_road->tileAt(_point + CCPoint(-1,0));
  544. if (_left)
  545. {
  546. m_moveObj->m_x = _point.x -1;
  547. m_moveObj->m_y = _point.y ;
  548. return;
  549. }
  550. CCSprite* _right = m_road->tileAt(_point + CCPoint(1,0));
  551. if (_right)
  552. {
  553. m_moveObj->m_x = _point.x + 1;
  554. m_moveObj->m_y = _point.y ;
  555. return;
  556. }
  557.  
  558. }
  559. #endif // PRECISE
  560. }
  561.  
  562. void PathSearchInfo::clearPath( )
  563. {
  564. for (vector<PathSprite*>::iterator iter = m_haveInspectList.begin(); iter != m_haveInspectList.end(); iter++)
  565. {
  566. (*iter)->m_sprite->setColor(ccWHITE);
  567. }
  568. resetInspectArray();
  569.  
  570. //把移除了障碍物的地图放入检测列表中
  571. //m_inspectList = m_mapList;
  572. m_openList.clear();
  573. m_pathList.clear();
  574. m_haveInspectList.clear();
  575. m_moveObj->m_startX = m_moveObj->m_x;
  576. m_moveObj->m_startY = m_moveObj->m_y;
  577. m_moveObj->m_sprite->stopAllActions();
  578.  
  579. m_playerMoveStep = 0;
  580. }
  581.  
  582.  
  583.  
  584. void PathSearchInfo::moveObj()
  585. {
  586. #ifndef PRECISE_SEARCH_PATH
  587. m_playerMoveStep++;
  588. m_isMoving = true;
  589. //如果运动完毕
  590. if (m_playerMoveStep >= m_pathList.size())
  591. {
  592. if (m_isSetMoveDoneCallback)
  593. {
  594. m_isMoving = false;
  595. m_moveDone(CCPoint((*(m_pathList.end()-1))->m_x,(*(m_pathList.end()-1))->m_y));
  596. }
  597. return;
  598. }
  599. //存储当前的移动进程
  600. m_moveObj->m_x = m_pathList[m_playerMoveStep]->m_x;
  601. m_moveObj->m_y = m_pathList[m_playerMoveStep]->m_y;
  602.  
  603. //设置深度
  604. m_moveObj->m_sprite->setZOrder(BASE_ZODER - m_pathList[m_playerMoveStep]->m_sprite->getPositionY());
  605.  
  606. //根据路径列表移动人物
  607. CCPoint _terminalPosition = m_pathList[m_playerMoveStep]->m_sprite->getPosition()+m_tileSize/2;
  608. float _length = MathLogic::calculateLengthrequiredTwoPoint(_terminalPosition,m_moveObj->m_sprite->getPosition());
  609. m_moveObj->m_sprite->runAction(CCSequence::create(CCMoveTo::create(MOVE_SPEED * _length,_terminalPosition),CCCallFunc::create(this,SEL_CallFunc(&PathSearchInfo::moveObj)),NULL));
  610. #else
  611. m_isMoving = true;
  612. if (m_playerMoveStep == m_pathList.size()-1)
  613. {
  614. //sitChairJudge();
  615. if (m_isSetMoveDoneCallback)
  616. {
  617. m_isMoving = false;
  618. m_moveDone(CCPoint((*(m_pathList.end()-1))->m_x,(*(m_pathList.end()-1))->m_y));
  619. }
  620. return ;
  621. }
  622.  
  623. for (int i = 1;i <= m_pathList.size() ;i++)
  624. {
  625. m_playerMoveStep = m_pathList.size()-i;
  626.  
  627. if(detectWhetherCanPassBetweenTwoPoints(CCPoint(m_moveObj->m_x,m_moveObj->m_y),CCPoint(m_pathList[m_playerMoveStep]->m_x,m_pathList[m_playerMoveStep]->m_y)))
  628. {
  629. CCPoint _terminalPosition = m_pathList[m_playerMoveStep]->m_sprite->getPosition()+m_tileSize/2;
  630. float _length = MathLogic::calculateLengthrequiredTwoPoint(_terminalPosition,m_moveObj->m_sprite->getPosition());
  631. m_moveObj->m_sprite->runAction(CCSequence::create(CCMoveTo::create(MOVE_SPEED * _length,NULL));
  632. //存储当前的移动进程
  633. m_moveObj->m_x = m_pathList[m_playerMoveStep]->m_x;
  634. m_moveObj->m_y = m_pathList[m_playerMoveStep]->m_y;
  635.  
  636. m_moveObj->m_sprite->setZOrder(BASE_ZODER - m_pathList[m_playerMoveStep]->m_sprite->getPositionY());
  637.  
  638. break;
  639. }
  640. }
  641.  
  642.  
  643. #endif
  644. }
  645.  
  646.  

  1. #pragma once
  2.  
  3. #include "cocos2d.h"
  4. #include "vector"
  5. #include "cocos-ext.h"
  6. using namespace std;
  7. USING_NS_CC;
  8. USING_NS_CC_EXT;
  9. class PathSprite
  10. {
  11. public:
  12. PathSprite(CCSprite* sprite):m_parent(NULL),m_child(NULL),m_costToSource(0),m_FValue(0),m_sprite(sprite),m_startX(0),m_startY(0),m_endX(0),m_endY(0)
  13. {
  14.  
  15. };
  16. public:
  17. CCSprite* m_sprite;//包含的瓦片精灵
  18. PathSprite* m_parent;//父节点
  19. PathSprite* m_child;//子节点
  20. float m_costToSource;//到起始点的距离
  21. int m_x;//地图坐标
  22. int m_y;
  23. float m_FValue;
  24.  
  25. int m_startX;//开始点
  26. int m_startY;
  27.  
  28. int m_endX;//结束点
  29. int m_endY;
  30.  
  31. };

  1. #pragma once
  2. #include "PathSprite.h"
  3. enum WalkState
  4. {
  5. WALK_LEFT,WALK_RIGHT,WALK_STAND
  6. };
  7.  
  8. class Player:public PathSprite
  9. {
  10. public:
  11. CCArmature *armature;
  12. WalkState m_walkState;
  13. public:
  14. Player(CCSprite* sprite);
  15. public:
  16. void walkLeft();
  17. void walkRight();
  18.  
  19. void stand();
  20. void walking();
  21. };

  1. #include "Player.h"
  2.  
  3. Player::Player(CCSprite* sprite):PathSprite(sprite)
  4. {
  5. //创建一个人物
  6. CCArmatureDataManager::sharedArmatureDataManager()->addArmatureFileInfo("DemoPlayer/DemoPlayer.ExportJson");
  7. armature = NULL;
  8. armature = CCArmature::create("DemoPlayer");//0走路,1开枪,2开枪,3开空枪,4
  9. armature->setAnchorPoint(CCPoint(0.7,0));
  10.  
  11. sprite->addChild(armature);
  12. }
  13.  
  14. void Player::walkLeft()
  15. {
  16. if (m_walkState == WALK_LEFT)
  17. {
  18. return;
  19. }
  20. armature->getAnimation()->playWithIndex(1);
  21. armature->setScaleX(1);
  22. m_walkState = WALK_LEFT;
  23. }
  24.  
  25. void Player::walkRight()
  26. {
  27. if (m_walkState == WALK_RIGHT)
  28. {
  29. return;
  30. }
  31. armature->getAnimation()->playWithIndex(1);
  32. armature->setScaleX(-1);
  33. m_walkState = WALK_RIGHT;
  34. }
  35.  
  36. void Player::stand()
  37. {
  38. if (m_walkState == WALK_STAND)
  39. {
  40. return;
  41. }
  42. if (m_walkState == WALK_LEFT)
  43. {
  44. armature->getAnimation()->playWithIndex(2);
  45. armature->setScaleX(1);
  46. }
  47. if (m_walkState == WALK_RIGHT)
  48. {
  49. armature->getAnimation()->playWithIndex(2);
  50. armature->setScaleX(-1);
  51. }
  52. m_walkState = WALK_STAND;
  53. }
  54.  
  55. void Player::walking()
  56. {
  57. if (m_endX - m_startX >=0)
  58. {
  59. walkRight();
  60. }
  61. else
  62. {
  63. walkLeft();
  64. }
  65. }

  1. #ifndef _PADDLE_H_
  2. #define _PADDLE_H_
  3.  
  4. #include "cocos2d.h"
  5. #include <functional>
  6. //#include "stdafx.h"
  7. //using namespace std;
  8.  
  9. USING_NS_CC;
  10.  
  11. typedef enum tagPaddleState
  12. {
  13. kPaddleStateGrabbed,kPaddleStateUngrabbed
  14. } PaddleState;
  15. enum OBJTYPE
  16. {
  17. NONE_TYPE = 0,CHAIR_LEFT = 1,CHAIR_FRON = 2,CHAIR_RIGHT = 3,CHAIR_BACK = 4
  18. };
  19. class Paddle : public CCSprite,public CCTargetedTouchDelegate
  20. {
  21. public:
  22. PaddleState m_state;
  23. bool m_isSelect;
  24. bool m_enableSit;
  25. bool m_enableTouch;
  26. bool m_enablePickUp;
  27. CCPoint m_terminal;
  28. std::function<void(CCPoint,Paddle* )> m_selectCallback;
  29. OBJTYPE m_type;
  30. CCSprite* m_playerSprite;
  31. CCSprite* m_chairPartSprite;
  32. public:
  33. Paddle(void);
  34. virtual ~Paddle(void);
  35.  
  36. CCRect rect();
  37. bool initWithTexture();
  38. virtual void onEnter();
  39. virtual void onExit();
  40. bool containsTouchLocation(CCPoint point);
  41. virtual bool ccTouchBegan(CCTouch* touch,CCEvent* event);
  42. virtual void ccTouchMoved(CCTouch* touch,CCEvent* event);
  43. virtual void ccTouchEnded(CCTouch* touch,CCEvent* event);
  44. virtual CCObject* copyWithZone(CCZone *pZone);
  45.  
  46. virtual void touchDelegateRetain();
  47. virtual void touchDelegateRelease();
  48.  
  49. static Paddle* paddleWithContentSize(CCSize);//创建物体
  50.  
  51. void setSelect(bool isSelect);//选中时
  52. void setOpacity(GLubyte opacity);
  53. void sitChair();//坐下
  54. void standUp();//站起
  55. };
  56.  
  57. #endif

  1. #include "Paddle.h"
  2. #include "FilePath.h"
  3. using namespace std;
  4. Paddle::Paddle(void):m_chairPartSprite(NULL),m_playerSprite(NULL),m_enableSit(false)
  5. {
  6. }
  7.  
  8. Paddle::~Paddle(void)
  9. {
  10. }
  11.  
  12. CCRect Paddle::rect()
  13. {
  14. CCSize s = this->getContentSize();
  15. return CCRectMake(this->getPositionX(),this->getPositionY(),s.width,s.height);
  16. }
  17.  
  18. Paddle* Paddle::paddleWithContentSize(CCSize size)
  19. {
  20. Paddle* pPaddle = new Paddle();
  21. pPaddle->initWithTexture();
  22. pPaddle->setContentSize(size);
  23.  
  24. pPaddle->autorelease();
  25.  
  26. return pPaddle;
  27. }
  28.  
  29. bool Paddle::initWithTexture()
  30. {
  31. if( CCSprite::init() )
  32. {
  33. m_state = kPaddleStateUngrabbed;
  34. }
  35.  
  36. return true;
  37. }
  38.  
  39. void Paddle::onEnter()
  40. {
  41. CCDirector* pDirector = CCDirector::sharedDirector();
  42. pDirector->getTouchDispatcher()->addTargetedDelegate(this,false);
  43. CCSprite::onEnter();
  44. }
  45.  
  46. void Paddle::onExit()
  47. {
  48. CCDirector* pDirector = CCDirector::sharedDirector();
  49. pDirector->getTouchDispatcher()->removeDelegate(this);
  50. CCSprite::onExit();
  51. }
  52.  
  53. bool Paddle::containsTouchLocation(CCPoint point)
  54. {
  55. //CCLog("%f,%f",convertToNodeSpaceAR(point).x,convertToNodeSpaceAR(point).y);
  56. return rect().containsPoint((point));
  57.  
  58. }
  59.  
  60. bool Paddle::ccTouchBegan(CCTouch* touch,CCEvent* event)
  61. {
  62. if (m_isSelect) {
  63. setSelect(false);
  64.  
  65. }
  66. auto nodePosition = this->getParent()->convertToNodeSpace( touch->getLocation() );
  67. CCLog("%f,nodePosition.x,nodePosition.y);
  68. if (m_state != kPaddleStateUngrabbed) return false;
  69. if ( !containsTouchLocation(nodePosition) ) return false;
  70. CCLog("touchSuccess") ;
  71. m_state = kPaddleStateGrabbed;
  72.  
  73. setSelect(true);
  74.  
  75. if (m_selectCallback)
  76. {
  77. m_selectCallback(m_terminal,this);
  78. }
  79. //sitChair();
  80.  
  81. return true;
  82. }
  83.  
  84. void Paddle::ccTouchMoved(CCTouch* touch,CCEvent* event)
  85. {
  86. // If it weren't for the TouchDispatcher,you would need to keep a reference
  87. // to the touch from touchBegan and check that the current touch is the same
  88. // as that one.
  89. // Actually,it would be even more complicated since in the Cocos dispatcher
  90. // you get CCSets instead of 1 UITouch,so you'd need to loop through the set
  91. // in each touchXXX method.
  92.  
  93. CCAssert(m_state == kPaddleStateGrabbed,"Paddle - Unexpected state!");
  94.  
  95. // CCPoint touchPoint = touch->getLocation();
  96.  
  97. //setPosition( ccp(touchPoint.x,getPosition().y) );
  98. }
  99.  
  100. CCObject* Paddle::copyWithZone(CCZone *pZone)
  101. {
  102. this->retain();
  103. return this;
  104. }
  105.  
  106. void Paddle::ccTouchEnded(CCTouch* touch,CCEvent* event)
  107. {
  108. CCAssert(m_state == kPaddleStateGrabbed,"Paddle - Unexpected state!");
  109.  
  110. m_state = kPaddleStateUngrabbed;
  111. }
  112.  
  113. void Paddle::touchDelegateRetain()
  114. {
  115. this->retain();
  116. }
  117.  
  118. void Paddle::touchDelegateRelease()
  119. {
  120. this->release();
  121. }
  122.  
  123. void Paddle::setSelect(bool isSelect)
  124. {
  125. CCArray* _array = this->getChildren();
  126. CCObject *_obj;
  127. m_isSelect = isSelect;
  128. CCARRAY_FOREACH(_array,_obj )
  129. {
  130. CCSprite* _sp = (CCSprite *)_obj;
  131. if (isSelect)
  132. {
  133. _sp->setColor(ccRED);
  134. }
  135. else
  136. {
  137. _sp->setColor(ccWHITE);
  138.  
  139. }
  140.  
  141. }
  142.  
  143.  
  144. }
  145.  
  146. void Paddle::setOpacity( GLubyte opacity )
  147. {
  148. CCArray* _array = this->getChildren();
  149. CCObject *_obj;
  150. CCARRAY_FOREACH(_array,_obj )
  151. {
  152. CCSprite* _sp = (CCSprite *)_obj;
  153. _sp->setOpacity(opacity);
  154. }
  155. }
  156.  
  157. void Paddle::sitChair()
  158. {
  159. switch (m_type)
  160. {
  161. case NONE_TYPE:
  162. break;
  163. case CHAIR_LEFT:
  164. {
  165. m_playerSprite = CCSprite::create(g_chair_left_player);
  166. m_playerSprite->setAnchorPoint(CCPoint());
  167. m_playerSprite->setPosition(CCPoint(-8,-15));
  168. this->addChild(m_playerSprite,100);
  169.  
  170. m_chairPartSprite= CCSprite::create(g_chair_left_part);
  171. m_chairPartSprite->setAnchorPoint(CCPoint());
  172. m_chairPartSprite->setPosition(CCPoint(-15,-5));
  173. this->addChild(m_chairPartSprite,100);
  174. break;
  175. }
  176. case CHAIR_FRON:
  177. break;
  178. case CHAIR_RIGHT:
  179. break;
  180. case CHAIR_BACK:
  181. {
  182.  
  183. m_playerSprite = CCSprite::create(g_chair_back_player);
  184. m_playerSprite->setAnchorPoint(CCPoint());
  185. m_playerSprite->setPosition(CCPoint(-15,-5));
  186. this->addChild(m_playerSprite);
  187. break;
  188. }
  189. default:
  190. break;
  191. }
  192. }
  193.  
  194. void Paddle::standUp()
  195. {
  196. if (m_playerSprite)
  197. {
  198. m_playerSprite->removeFromParentAndCleanup(true);
  199. m_playerSprite = NULL;
  200. }
  201. if (m_chairPartSprite)
  202. {
  203. m_chairPartSprite->removeFromParentAndCleanup(true);
  204. m_chairPartSprite = NULL;
  205. }
  206. }

  1. //
  2. // MathLogic.h
  3. // MapGame
  4. //
  5. // Created by TinyUlt on 14/10/11.
  6. //
  7. //
  8.  
  9. #ifndef __MapGame__MathLogic__
  10. #define __MapGame__MathLogic__
  11.  
  12. #include <stdio.h>
  13. #include "cocos2d.h"
  14. USING_NS_CC;
  15. class MathLogic
  16. {
  17. public:
  18. //线性方程 一元二次方法 求y
  19. static float linearEquationWithOneUnknown_solveYrequiredX(CCPoint knownPoint1,CCPoint knownPoint2,float x)
  20. {
  21. float _x1 = knownPoint1.x;
  22. float _y1 = knownPoint1.y;
  23. float _x2 = knownPoint2.x;
  24. float _y2 = knownPoint2.y;
  25. float m_p1 = (_y1 -_y2)/(_x1-_x2);
  26. float m_p2 = _y1 - m_p1 * _x1;
  27. // float m_p1 = (knownPoint1.y -knownPoint2.y)/(knownPoint1.x-knownPoint2.x);
  28. // float m_p2 = knownPoint1.y - m_p1 * knownPoint1.x;
  29.  
  30. return m_p1* x + m_p2;
  31. }
  32.  
  33. //线性方程 一元二次方法 求x
  34. static float linearEquationWithOneUnknown_solveXrequiredY(CCPoint knownPoint1,float y)
  35. {
  36. float _x1 = knownPoint1.x;
  37. float _y1 = knownPoint1.y;
  38. float _x2 = knownPoint2.x;
  39. float _y2 = knownPoint2.y;
  40. float m_p1 = (_y1 -_y2)/(_x1-_x2);
  41. float m_p2 = _y1 - m_p1 * _x1;
  42. // float m_p1 = (knownPoint1.y -knownPoint2.y)/(knownPoint1.x-knownPoint2.x);
  43. // float m_p2 = knownPoint1.y - m_p1 * knownPoint1.x;
  44.  
  45. return (y - m_p2)/m_p1;
  46. }
  47.  
  48. //求点到直线最短路径长度
  49. static float linearEquationWithOneUnknown_solveShortLenghtrequiredPoint(CCPoint knownPoint1,CCPoint point)
  50. {
  51. if ((point.x == knownPoint1.x && point.y == knownPoint1.y) || (point.x == knownPoint2.x && point.y == knownPoint2.y))
  52. {
  53. return 0;
  54. }
  55.  
  56. float _x1 = knownPoint1.x;
  57. float _y1 = knownPoint1.y;
  58. float _x2 = knownPoint2.x;
  59. float _y2 = knownPoint2.y;
  60. float m_p1 = (_y1 -_y2)/(_x1-_x2);
  61. float m_p2 = _y1 - m_p1 * _x1;
  62.  
  63. CCPoint p1((point.y - m_p2)/m_p1,point.y);
  64. CCPoint p2(point.x,m_p1* point.x + m_p2);
  65. float offsetY = abs( p2.y - point.y);
  66. float offsetX = abs(p1.x - point.x);
  67.  
  68. if (offsetX == 0 && offsetY == 0)
  69. {
  70. return 0;
  71. }
  72.  
  73.  
  74. return offsetX * offsetY / calculateLengthrequiredTwoPoint(p1,p2);
  75. }
  76.  
  77. //计算2点距离
  78. static float calculateLengthrequiredTwoPoint(CCPoint p1,CCPoint p2)
  79. {
  80. float _offsetX = abs( p1.x - p2.x);
  81. float _offsetY =abs( p1.y - p2.y);
  82. return sqrt(_offsetX * _offsetX + _offsetY * _offsetY);
  83. }
  84.  
  85. //绝对值
  86. static float abs(float value)
  87. {
  88. return value>0?value:-value;
  89. }
  90. };
  91. #endif /* defined(__MapGame__MathLogic__) */

  1. #ifndef __HELLOWORLD_SCENE_H__
  2. #define __HELLOWORLD_SCENE_H__
  3. #include "PathSearchInfo.h"
  4. #include "Player.h"
  5. class Paddle;
  6. class HelloWorld : public cocos2d::CCLayer
  7. {
  8. public:
  9. // Here's a difference. Method 'init' in cocos2d-x returns bool,instead of returning 'id' in cocos2d-iphone
  10. virtual bool init();
  11.  
  12. // there's no 'id' in cpp,so we recommend returning the class instance pointer
  13. static cocos2d::CCScene* scene();
  14.  
  15. // a selector callback
  16. void menuCloseCallback(CCObject* pSender);
  17.  
  18. // implement the "static node()" method manually
  19. CREATE_FUNC(HelloWorld);
  20. void onEnter();
  21. virtual bool ccTouchBegan(CCTouch* touch,CCEvent* event);
  22.  
  23. void drawPath(vector<PathSprite*>& vec);//绘制路径(测试用)
  24.  
  25. void update(float dt);//跟新大地图(行走时,人不动,地图跟着人动);
  26.  
  27. void selectObjCallback(CCPoint point,Paddle* selectObj);//选择物体回调
  28.  
  29. void moveDone(CCPoint point);//移动结束回调
  30.  
  31. public:
  32. PathSearchInfo* m_pathSearch;//寻路引擎类
  33.  
  34. CCPoint m_orignPoint;//人物的起始点
  35.  
  36. Player* m_player;//人物
  37.  
  38. Paddle* m_currentSelect;//当前选中的物品
  39. };
  40. #endif // __HELLOWORLD_SCENE_H__

  1. #include "HelloWorldScene.h"
  2. #include "Paddle.h"
  3. #include "MathLogic.h"
  4. #include <functional>
  5. USING_NS_CC;
  6.  
  7.  
  8. CCScene* HelloWorld::scene()
  9. {
  10. // 'scene' is an autorelease object
  11. CCScene *scene = CCScene::create();
  12.  
  13. // 'layer' is an autorelease object
  14. HelloWorld *layer = HelloWorld::create();
  15.  
  16. // add layer as a child to scene
  17. scene->addChild(layer);
  18.  
  19. // return the scene
  20. return scene;
  21. }
  22.  
  23. // on "init" you need to initialize your instance
  24. void HelloWorld::onEnter()
  25. {
  26. CCDirector* pDirector = CCDirector::sharedDirector();
  27. pDirector->getTouchDispatcher()->addTargetedDelegate(this,-1,false);
  28. CCLayer::onEnter();
  29.  
  30. }
  31.  
  32. bool HelloWorld::init()
  33. {
  34. //////////////////////////////
  35. // 1. super init first
  36. if ( !CCLayer::init() )
  37. {
  38. return false;
  39. }
  40. CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
  41. CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
  42.  
  43. CCTMXTiledMap* _map = CCTMXTiledMap::create("gameMap.tmx");
  44. _map->setPosition(CCPoint());
  45. this->addChild(_map);
  46.  
  47. m_pathSearch = new PathSearchInfo(_map);
  48.  
  49. std::function<void (CCPoint point)> _fun = std::bind(&HelloWorld::moveDone,this,std::placeholders::_1);
  50. m_pathSearch->setMoveDoneCallback(_fun);
  51.  
  52. std::function<void (vector<PathSprite*>)> _funDrawPath = std::bind(&HelloWorld::drawPath,std::placeholders::_1);
  53. m_pathSearch->setDrawPathCallback(_funDrawPath);
  54.  
  55. std::function<void(CCPoint point,Paddle* selectObj)> _funcSelect = std::bind(&HelloWorld::selectObjCallback,std::placeholders::_1,std::placeholders::_2);
  56. m_pathSearch->setSelectCallback(_funcSelect);
  57. /////////////////////////////
  58. CCMenuItemSprite* _menuItemSprite = CCMenuItemSprite::create(CCSprite::create("CloseNormal.png"),CCSprite::create("CloseSelected.png"),SEL_MenuHandler(&HelloWorld::menuCloseCallback));
  59. CCMenu* _menu = CCMenu::create(_menuItemSprite,NULL);
  60. this->addChild(_menu,1000);
  61.  
  62. m_currentSelect = NULL;
  63.  
  64. //m_isMoving = false;
  65. CCLabelTTF* pLabel = CCLabelTTF::create("A* + tiledMap","Arial",24);
  66.  
  67. // position the label on the center of the screen
  68. pLabel->setPosition(ccp(origin.x + visibleSize.width/2,origin.y + visibleSize.height - pLabel->getContentSize().height));
  69.  
  70. // add the label as a child to this layer
  71. this->addChild(pLabel,1);
  72.  
  73. this->scheduleUpdate();
  74.  
  75. //设置起始和终点
  76. m_orignPoint = CCDirector::sharedDirector()->getWinSize()/2 ;//+ CCSize(0,100);
  77. //创建一个人物
  78. CCSprite* _sp = CCSprite::create();
  79. _sp->setScale(0.08);
  80.  
  81. m_player = new Player(_sp);
  82. m_player->m_sprite->setOpacity(100);
  83. m_pathSearch->getMap()->addChild(m_player->m_sprite,BASE_ZODER);
  84. m_player->m_sprite->setPosition(m_orignPoint);//设置人物的起始的世界坐标
  85. m_player->m_startX =m_pathSearch->getMapPositionByWorldPosition(m_orignPoint).x;
  86. m_player->m_startY =m_pathSearch->getMapPositionByWorldPosition(m_orignPoint).y;
  87. m_player->m_x = m_player->m_startX;
  88. m_player->m_y = m_player->m_startY;
  89.  
  90. m_pathSearch->initMapObject("desk","desk");
  91. m_pathSearch->initMapObject("chairLeft","chairLeft");
  92. m_pathSearch->initMapObject("chairFront","chairFront");
  93. m_pathSearch->initMapObject("chairBack","chairBack");
  94. m_pathSearch->initMapObject("zhuzi","zhuzi");
  95. m_pathSearch->initMapObject("goods","goods");
  96. return true;
  97. }
  98.  
  99. void HelloWorld::drawPath( vector<PathSprite*>& vec )
  100. {
  101. for (vector<PathSprite*>::iterator iter = vec.begin(); iter != vec.end(); iter++)
  102. {
  103. (*iter)->m_sprite->setColor(ccGREEN);
  104. }
  105. }
  106.  
  107. CCRect getBoundingBox(float x,float y,float width,float height)
  108. {
  109. return CCRect(x - width/2,y - height/2,width,height);
  110. }
  111.  
  112. bool HelloWorld::ccTouchBegan(CCTouch* touch,CCEvent* event)
  113. {
  114. if (m_pathSearch->getEnableMove())
  115. {
  116. m_currentSelect = NULL;
  117. auto nodePosition = convertToNodeSpace( touch->getLocation() );
  118. m_pathSearch ->pathFunction(m_pathSearch->getMapPositionByWorldPosition(nodePosition),m_player);
  119. }
  120. return true;
  121. }
  122.  
  123. void HelloWorld::ccTouchMoved(CCTouch* touch,CCEvent* event)
  124. {
  125.  
  126. }
  127.  
  128. void HelloWorld::ccTouchEnded(CCTouch* touch,CCEvent* event)
  129. {
  130.  
  131. }
  132.  
  133. void HelloWorld::menuCloseCallback(CCObject* pSender)
  134. {
  135. if (!m_pathSearch->getEnableMove())
  136. {
  137. m_pathSearch->setEnableMove(true);
  138. m_currentSelect->standUp();
  139. m_player->m_sprite->setVisible(true);
  140. }
  141. }
  142. void HelloWorld::update(float dt)
  143. {
  144. //移动层
  145. this->setPosition(m_orignPoint - m_player->m_sprite->getPosition());
  146.  
  147. if(m_pathSearch->getIsMoving())
  148. {
  149. m_player->walking();
  150. }
  151. else
  152. {
  153. m_player->stand();
  154. }
  155. }
  156.  
  157. void HelloWorld::selectObjCallback( CCPoint point,Paddle* selectObj )
  158. {
  159. //如果不能移动物体的话,不能点击其他物体
  160. if (m_pathSearch->getEnableMove())
  161. {
  162. m_currentSelect = selectObj;
  163.  
  164. m_pathSearch ->pathFunction( point,m_player);
  165. }
  166. }
  167.  
  168. void HelloWorld::moveDone(CCPoint point)
  169. {
  170. //判断是有选择的物体
  171. if (m_currentSelect)
  172. {
  173. //判断是否能坐下
  174. if (m_currentSelect->m_enableSit/* && point.x == m_currentSelect->m_terminal.x&& point.y == m_currentSelect->m_terminal.y*/)
  175. {
  176. m_currentSelect->sitChair();
  177. m_pathSearch->setEnableMove(false);
  178. m_player->m_sprite->setVisible(false);
  179. }
  180. //判断是否能捡起
  181. if (m_currentSelect->m_enablePickUp)
  182. {
  183. m_currentSelect->m_enablePickUp = false;
  184. m_currentSelect->runAction(CCSequence::create(CCFadeOut::create(0.5),CCRemoveSelf::create(true),NULL));
  185. m_currentSelect = NULL;
  186. }
  187. }
  188. }
  189.  
  190.  
  191.  
  192.  
  193.  

  1. static char* g_chair_left_player = "player_1/chair_left_player.png";
  2. static char* g_chair_back_player = "player_1/chair_back_player.png";
  3. static char* g_chair_left_part = "player_1/chair_left_part.png";

  1. #define MAP_WIDTH 600//要比tmx中的map大1
  2. #define MAP_HEIGHT 600
  3. #define BASE_ZODER 100000
  4. #define MOVE_SPEED 1/200.0
  5.  
  6. #define PRECISE_SEARCH_PATH//精确的寻 路系统,需要消耗额外的运算(魔兽争霸级的!)

猜你在找的Cocos2d-x相关文章