A collection of nodes that describes the navigability of a game world and provides pathfinding methods to search for routes through that space.
- iOS 9.0+
- macOS 10.11+
- Mac Catalyst 13.0+
- tvOS 9.0+
Individual nodes in a graph represent discrete locations that a character or other object in your game can occupy, and the connections between adjacent nodes represent the ability of a game entity to travel from one location to another. Use the
GKGraph class to create a general graph, or the
GKMesh subclass to generate specialized graphs that contain more information about the geometry of your game world.
Each set of graph and node classes can generate graphs for different kinds of spaces:
The base classes
GKGraphcontain functionality general to all graphs and nodes. You can also use these classes on their own to construct graphs that contain no geometry information. This option is useful for games where the connections between spaces are more important than their physical locations, such as board games.
GKMeshclass to describe 2D game worlds that allow continuous movement in open spaces that are interrupted by impassable obstacles (
GKPolygonobjects). Obstacle graphs automatically generate nodes containing 2D point information (
GKGraphobjects), and you can also add your own such nodes representing locations of interest.
The graphs modeled by this class are always directed—that is, a connection between two nodes describes one direction of travel between them. To enable travel between two nodes in either direction, you must create a connection in each direction. You can choose to connect both directions at once with the
connect method (for graphs) or the addConnection:bidirectional: method (for nodes).
Using a graph for pathfinding typically involves three major steps:
Create a graph once (for example, when initializing a game level class) with static information about your game world.
When you need to find a route between points, connect temporary nodes to the graph at those points. Use the
connectmethod to connect nodes using their own geometry information, or the
To Lowest Cost Node(node: bidirectional:)
connectmethod to use the additional constraints of obstacle and grid graphs.
To Adjacent Nodes(node:)
findmethod to find a route between locations in the graph. This method returns an array of graph nodes, starting with the requested start point of the path, and proceeding to adjacent nodes in order until it reaches the requested end point. Use the geometry information contained in each node to make use of the route—for example, in a SpriteKit game you might create a sequence of move actions to move a character from point to point along the path.
The temporary nodes you created for finding a path typically have little usefulness after a path has been found. Remove those nodes before reusing the graph for future searches.