2

I am making a Topdown 2d game in SDL2 with C++. It has a tiled map of each tile being 32x32 px in dimensions.

I have used the A* search algorithm so the enemy can find the player in the map. Currently the path is being correctly traced and after performing A*, it returns a stack of SDL_Point which are just x and y values on map. But I can't figure out how to make the enemy follow this path slowly overtime rather than just hopping on x and y points in the stack.

Below is the move function, the move function is constantly called in the main game loop:


void Gunner::move(std::array<Tile*, MAP_LENGTH>& map, double deltaTime) {

    // calculate A* path from current pos to player pos
    Astar astar(target, this);

    stack<SDL_Point> path = astar.astar(map);

    if (path.size() != 0) {
        SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);

        int xP = path.top().x;
        int yP = path.top().y;

        SDL_Rect r = { xP, yP, 32, 32 };

        /*
            Make the enemy follow path
        */

        // debugging purpose
        SDL_RenderFillRect(renderer, &r);
        path.pop();
    }
}

This is the path generated where e is enemy and p is player.

Game screenshot

Ali Ahmed
  • 164
  • 2
  • 12

1 Answers1

1

The keyword you're looking for is "path smoothing". There are lots of ways to implement this, which are too complex for a single Stackoverflow answer:

  • I believe the most popular option is string pulling, which, as the name suggests, is like pulling on your path as though it were a string to make it taut.
  • You could also use the grid points to generate a spline.
  • You could use a steering algorithm to have your unit approximate the path.

Another option that has become more popular in recent years is to use an "any-angle" path-finding algorithm, which generates smoothed paths from the get-go. Theta* is the most popular one, to my knowledge.

All of these options produce near-optimal results. If for some reason you need optimal results, this paper was released a few years ago. I don't know much about it, but I assume it's slower than the other options.

Here is a github page with a lot more options for path smoothing.

BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283