How to implement A * pathfinding Algorithm in Cocos2D games (V)

Source: Internet
Author: User

How to implement A * pathfinding Algorithm in Cocos2D games (V)

 

Move forward with the yellow bricks

Now we have found our path. We only need to let the cat follow it.

What we need to do next is to remember the entire path and move the cat step by step based on the path.

Create an array of storage paths in CatSprite. h and add the following in the private section of @ interface of CatSprite:

NSMutableArray *shortestPath;

Then, modify CatSprite. m as follows:

// Add inside the CatSprite private properties and methods section@property (nonatomic, retain) NSMutableArray *shortestPath;// After the CatSprite @implementation@synthesize shortestPath;// Inside initWithLayerself.shortestPath = nil;// Inside dealloc   [shortestPath release]; shortestPath = nil;

Now we will create a method to store the entire path and manage the animation to start, and complete the following modifications in CatSprite. m:

// Add inside the CatSprite private properties and methods section- (void)constructPathAndStartAnimationFromStep:(ShortestPathStep *)step;// Inside moveToward, comment out the pathFound BOOL//BOOL pathFound = NO;// Inside moveToward, replace pathFound = YES with this:[self constructPathAndStartAnimationFromStep:currentStep];// Also comment all of the debugging statements below that.// Inside moveToward, replace if (!pathFound) with this:if (self.shortestPath == nil) { // No path found// Add this new method:// Go backward from a step (the final one) to reconstruct the shortest computed path- (void)constructPathAndStartAnimationFromStep:(ShortestPathStep *)step{    self.shortestPath = [NSMutableArray array];    do {        if (step.parent != nil) { // Don't add the last step which is the start position (remember we go backward, so the last one is the origin position ;-)            [self.shortestPath insertObject:step atIndex:0]; // Always insert at index 0 to reverse the path        }        step = step.parent; // Go backward    } while (step != nil); // Until there is no more parents    for (ShortestPathStep *s in self.shortestPath) {        NSLog(@%@, s);    }}

Note: In the moveToward method, we call a new method to replace the original code that prints the result on the console, and delete the pathFound variable. as usual, the comments in the constructPathAndStartAnimationFromStep method explain in detail what actually happened.

Compile and run now. If you touch the same tile as we mentioned earlier, you should see the following log:


  
     pos=[24;1]  g=1  h=4  f=5
   
      pos=[23;1]  g=2  h=3  f=5
    
       pos=[22;1]  g=3  h=2  f=5
     
        pos=[21;1]  g=4  h=3  f=7
      
        pos=[20;1] g=5 h=4 f=9
       
         pos=[20;2] g=6 h=3 f=9
        
          pos=[20;3] g=7 h=2 f=9
         
           pos=[21;3] g=8 h=1 f=9
          
            pos=[22;3] g=9 h=0 f=9
          
         
        
       
      
     
    
   
  

Note that it is similar to the previous one, except that it is from the beginning to the end (reverse the previous result) and the data stored in the array is easier for us to use.

The last thing to do is to traverse the shortestPath array and display the path followed by the CAT in an animation. to achieve this goal, we will create a method to pop up the data in each step from the array, so that the cat can move to this location, and add a callback method to call this method repeatedly until the path is complete.

Complete the following changes in CatSprite. m:

// Add inside the CatSprite private properties and methods section- (void)popStepAndAnimate;// Add to bottom of constructPathAndStartAnimationFromStep[self popStepAndAnimate];// Add new method- (void)popStepAndAnimate{       // Check if there remains path steps to go through    if ([self.shortestPath count] == 0) {        self.shortestPath = nil;        return;    }    // Get the next step to move to    ShortestPathStep *s = [self.shortestPath objectAtIndex:0];    // Prepare the action and the callback    id moveAction = [CCMoveTo actionWithDuration:0.4 position:[_layer positionForTileCoord:s.position]];    id moveCallback = [CCCallFunc actionWithTarget:self selector:@selector(popStepAndAnimate)]; // set the method itself as the callback    // Remove the step    [self.shortestPath removeObjectAtIndex:0];    // Play actions    [self runAction:[CCSequence actions:moveAction, moveCallback, nil]];}

Compile and run...

 

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.