Let’s Make: Traffic Department 2192 – Part 28

Prototyping - Programming AI

The 'intelligence' part of our AI is simply just finding a path between 2 points. We'll use the A* algorithm on our collision map to produce arbitrary paths through the world. We'll use the paths to take enemy fighting ships to the player and then back to the mission path.

The design of this segment was covered in part 23.

GML Code

We add no new objects in this segment. We'll only be altering the obj_ship_ai object and adding a few scripts that support the A* algorithm

obj_ship_ai: Begin Step 3

Now that we're adding the active AI, we need to start by determining which AI mode the NPC should be be in. This is based mostly on the type of ship (combat or not) and the distance of the closest opponent ship.

 

obj_ship_ai: Begin Step 4

When the NPC is hunting a target, we need it to find a path to it with A* or follow the A* path if it already has one.

 

obj_ship_ai: Begin Step 5

This handles the AI case where the ship is going back to the original mission path. If there is no planned path, it calls A* to find a valid path. If there it, is follows it until it's back on track.

 

Script: find_closest_opponent

This script loops through all ships and finds the closest opponent.

 

Script: id_to_map_x

Since I use unique IDs for each grid position, I need to convert that to the x grid coordinate

 

Script: id_to_map_y

Likewise for the y grid coordinate

 

Script: mh_dist

This is our heuristic for A*: The Manhattan Distance. Probably the best we can use in a 2D grid world.

 

Script: ai_star

Implementation of A* in GML.

 

Script: map_pos_to_id

Converts a map position given both coordinates to a unique value.