Full directional movement of player in cocos2D tilemap


/ Published in: Objective C
Save to your folder(s)



Copy this code and paste it in your HTML
  1. -(void) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
  2. {
  3.  
  4. BOOL moveX, moveY = NO;
  5.  
  6. CGPoint touchLocation = [touch locationInView: [touch view]];
  7. touchLocation = [[CCDirector sharedDirector] convertToGL: touchLocation];
  8. touchLocation = [self convertToNodeSpace:touchLocation];
  9.  
  10. CGPoint playerPos = _player.position;
  11. CGPoint diff = ccpSub(touchLocation, playerPos);
  12. CGSize winSize = [[CCDirector sharedDirector] winSize];
  13.  
  14. // Define areas on the screen to control player differently
  15. // Centralised cross that will move directly up, down, left or right (winsize.width/3, winsize.height/3)
  16. // Remaining areas will move diagonally
  17. // If central crossover area is pressed, player will not move.
  18.  
  19. // Left/right press
  20. if (touchLocation.x < winSize.width/3) {
  21. moveX = YES;
  22. } else if (touchLocation.x > ((winSize.width/3)*2)) {
  23. moveX = YES;
  24. } else {
  25. moveX = NO;
  26. }
  27.  
  28.  
  29. // Up/down press
  30. if (touchLocation.y < winSize.height/3) {
  31. moveY = YES;
  32. } else if (touchLocation.y > ((winSize.height/3)*2)) {
  33. moveY = YES;
  34. } else {
  35. moveY = NO;
  36. }
  37.  
  38.  
  39.  
  40. if (moveX) {
  41. if (diff.x >= _tileMap.tileSize.width) {
  42. playerPos.x += _tileMap.tileSize.width;
  43. } else if (diff.x <= (_tileMap.tileSize.width * -1)) {
  44. playerPos.x -= _tileMap.tileSize.width;
  45. }
  46. }
  47.  
  48. if (moveY) {
  49. if (diff.y >= _tileMap.tileSize.height) {
  50. playerPos.y += _tileMap.tileSize.height;
  51. } else if (diff.y <= (_tileMap.tileSize.height * -1)) {
  52. playerPos.y -= _tileMap.tileSize.height;
  53. }
  54. }
  55.  
  56.  
  57. if (moveX || moveY) {
  58.  
  59. if (playerPos.x <= (_tileMap.mapSize.width * _tileMap.tileSize.width) &&
  60. playerPos.y <= (_tileMap.mapSize.height * _tileMap.tileSize.height) &&
  61. playerPos.y >= 0 &&
  62. playerPos.x >= 0 )
  63. {
  64. [self setPlayerPosition:playerPos];
  65. }
  66.  
  67.  
  68. }
  69. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.