AStar Class |
A* (A star) is a computer algorithm that is widely used in pathfinding and graph traversal, the process of plotting short paths among vertices (points), passing through a given set of edges (segments). It enjoys widespread use due to its performance and accuracy. Godot's A* implementation uses points in three-dimensional space and Euclidean distances by default.
You must add points manually with AddPoint(Int32, Vector3, Single) and create segments manually with ConnectPoints(Int32, Int32, Boolean). Then you can test if there is a path between two points with the ArePointsConnected(Int32, Int32, Boolean) function, get a path containing indices by GetIdPath(Int32, Int32), or one containing actual coordinates with GetPointPath(Int32, Int32).
It is also possible to use non-Euclidean distances. To do so, create a class that extends AStar and override methods _ComputeCost(Int32, Int32) and _EstimateCost(Int32, Int32). Both take two indices and return a length, as is shown in the following example.
class MyAStar: extends AStar func _compute_cost(u, v): return abs(u - v) func _estimate_cost(u, v): return min(0, abs(u - v) - 1)
_EstimateCost(Int32, Int32) should return a lower bound of the distance, i.e. _estimate_cost(u, v) <= _compute_cost(u, v). This serves as a hint to the algorithm because the custom _compute_cost might be computation-heavy. If this is not the case, make _EstimateCost(Int32, Int32) return the same value as _ComputeCost(Int32, Int32) to provide the algorithm with the most accurate information.
If the default _EstimateCost(Int32, Int32) and _ComputeCost(Int32, Int32) methods are used, or if the supplied _EstimateCost(Int32, Int32) method returns a lower bound of the cost, then the paths returned by A* will be the lowest cost paths. Here, the cost of a path equals to the sum of the _ComputeCost(Int32, Int32) results of all segments in the path multiplied by the weight_scales of the end points of the respective segments. If the default methods are used and the weight_scales of all points are set to 1.0, then this equals to the sum of Euclidean distances of all segments in the path.
Namespace: Godot
public class AStar : Reference
The AStar type exposes the following members.
Name | Description | |
---|---|---|
![]() | DynamicObject |
Gets a new DynamicGodotObject associated with this instance.
(Inherited from Object.) |
![]() | NativeInstance | (Inherited from Object.) |
Name | Description | |
---|---|---|
![]() | _ComputeCost | Called when computing the cost between two connected points. Note that this function is hidden in the default AStar class. |
![]() | _EstimateCost | Called when estimating the cost between a point and the path's ending point. Note that this function is hidden in the default AStar class. |
![]() | _Get | Virtual method which can be overridden to customize the return value of Get(String). Returns the given property. Returns null if the property does not exist. |
![]() | _GetPropertyList | Virtual method which can be overridden to customize the return value of GetPropertyList. Returns the object's property list as an Array of dictionaries. Each property's Dictionary must contain at least name: String and type: int (see VariantType) entries. Optionally, it can also include hint: int (see PropertyHint), hint_string: String, and usage: int (see PropertyUsageFlags). |
![]() | _Notification | Called whenever the object receives a notification, which is identified in what by a constant. The base Object has two constants and , but subclasses such as Node define a lot more notifications which are also received by this method. |
![]() | _Set | Virtual method which can be overridden to customize the return value of Set(String, Object). Sets a property. Returns true if the property exists. |
![]() | AddPoint | Adds a new point at the given position with the given identifier. The id must be 0 or larger, and the weight_scale must be 1 or larger. The weight_scale is multiplied by the result of _ComputeCost(Int32, Int32) when determining the overall cost of traveling across a segment from a neighboring point to this point. Thus, all else being equal, the algorithm prefers points with lower weight_scales to form a path. var astar = AStar.new() astar.add_point(1, Vector3(1, 0, 0), 4) # Adds the point (1, 0, 0) with weight_scale 4 and id 1 If there already exists a point for the given id, its position and weight scale are updated to the given values. |
![]() | AddUserSignal | Adds a user-defined signal. Arguments are optional, but can be added as an Array of dictionaries, each containing name: String and type: int (see VariantType) entries. |
![]() | ArePointsConnected | Returns whether the two given points are directly connected by a segment. If bidirectional is false, returns whether movement from id to to_id is possible through this segment. |
![]() | Call | Calls the method on the object and returns the result. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example: call("set", "position", Vector2(42.0, 0.0)) Note: In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase). |
![]() | CallDeferred | Calls the method on the object during idle time. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example: call_deferred("set", "position", Vector2(42.0, 0.0)) Note: In C#, the method name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined methods where you should use the same convention as in the C# source (typically PascalCase). |
![]() | Callv | Calls the method on the object and returns the result. Contrarily to Call(String, Object), this method does not support a variable number of arguments but expects all parameters to be via a single Array. callv("set", [ "position", Vector2(42.0, 0.0) ]) |
![]() | CanTranslateMessages | Returns true if the object can translate strings. See SetMessageTranslation(Boolean) and Tr(String). |
![]() | Clear | Clears all the points and segments. |
![]() | Connect | Connects a signal to a method on a target object. Pass optional binds to the call as an Array of parameters. These parameters will be passed to the method after any parameter used in the call to EmitSignal(String, Object). Use flags to set deferred or one-shot connections. See ObjectConnectFlags constants. A signal can only be connected once to a method. It will throw an error if already connected, unless the signal was connected with . To avoid this, first, use IsConnected(String, Object, String) to check for existing connections. If the target is destroyed in the game's lifecycle, the connection will be lost. Examples: connect("pressed", self, "_on_Button_pressed") # BaseButton signal connect("text_entered", self, "_on_LineEdit_text_entered") # LineEdit signal connect("hit", self, "_on_Player_hit", [ weapon_type, damage ]) # User-defined signal An example of the relationship between binds passed to Connect(String, Object, String, Array, UInt32) and parameters used when calling EmitSignal(String, Object): connect("hit", self, "_on_Player_hit", [ weapon_type, damage ]) # weapon_type and damage are passed last emit_signal("hit", "Dark lord", 5) # "Dark lord" and 5 are passed first func _on_Player_hit(hit_by, level, weapon_type, damage): print("Hit by %s (lvl %d) with weapon %s for %d damage" % [hit_by, level, weapon_type, damage]) |
![]() | ConnectPoints | Creates a segment between the given points. If bidirectional is false, only movement from id to to_id is allowed, not the reverse direction. var astar = AStar.new() astar.add_point(1, Vector3(1, 1, 0)) astar.add_point(2, Vector3(0, 5, 0)) astar.connect_points(1, 2, false) |
![]() | Disconnect | Disconnects a signal from a method on the given target. If you try to disconnect a connection that does not exist, the method will throw an error. Use IsConnected(String, Object, String) to ensure that the connection exists. |
![]() | DisconnectPoints | Deletes the segment between the given points. If bidirectional is false, only movement from id to to_id is prevented, and a unidirectional segment possibly remains. |
![]() | Dispose | (Inherited from Object.) |
![]() | Dispose(Boolean) | (Inherited from Object.) |
![]() | EmitSignal | Emits the given signal. The signal must exist, so it should be a built-in signal of this class or one of its parent classes, or a user-defined signal. This method supports a variable number of arguments, so parameters are passed as a comma separated list. Example: emit_signal("hit", weapon_type, damage) emit_signal("game_over") |
![]() | Equals | (Inherited from Object.) |
![]() | Finalize | (Inherited from Object.) |
![]() | Free | Deletes the object from memory immediately. For Nodes, you may want to use QueueFree to queue the node for safe deletion at the end of the current frame. Important: If you have a variable pointing to an object, it will not be assigned to null once the object is freed. Instead, it will point to a previously freed instance and you should validate it with @GDScript.is_instance_valid before attempting to call its methods or access its properties. |
![]() | Get | Returns the Variant value of the given property. If the property doesn't exist, this will return null. Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase). |
![]() | GetAvailablePointId | Returns the next available point ID with no point associated to it. |
![]() | GetClass | Returns the object's class as a String. |
![]() | GetClosestPoint | Returns the ID of the closest point to to_position, optionally taking disabled points into account. Returns -1 if there are no points in the points pool. Note: If several points are the closest to to_position, the one with the smallest ID will be returned, ensuring a deterministic result. |
![]() | GetClosestPositionInSegment | Returns the closest position to to_position that resides inside a segment between two connected points. var astar = AStar.new() astar.add_point(1, Vector3(0, 0, 0)) astar.add_point(2, Vector3(0, 5, 0)) astar.connect_points(1, 2) var res = astar.get_closest_position_in_segment(Vector3(3, 3, 0)) # Returns (0, 3, 0) The result is in the segment that goes from y = 0 to y = 5. It's the closest position in the segment to the given point. |
![]() | GetHashCode | (Inherited from Object.) |
![]() | GetIdPath | Returns an array with the IDs of the points that form the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path. var astar = AStar.new() astar.add_point(1, Vector3(0, 0, 0)) astar.add_point(2, Vector3(0, 1, 0), 1) # Default weight is 1 astar.add_point(3, Vector3(1, 1, 0)) astar.add_point(4, Vector3(2, 0, 0)) astar.connect_points(1, 2, false) astar.connect_points(2, 3, false) astar.connect_points(4, 3, false) astar.connect_points(1, 4, false) var res = astar.get_id_path(1, 3) # Returns [1, 2, 3] If you change the 2nd point's weight to 3, then the result will be [1, 4, 3] instead, because now even though the distance is longer, it's "easier" to get through point 4 than through point 2. |
![]() | GetIncomingConnections | Returns an Array of dictionaries with information about signals that are connected to the object. Each Dictionary contains three String entries: - source is a reference to the signal emitter. - signal_name is the name of the connected signal. - method_name is the name of the method to which the signal is connected. |
![]() | GetIndexed | Gets the object's property indexed by the given NodePath. The node path should be relative to the current object and can use the colon character (:) to access nested properties. Examples: "position:x" or "material:next_pass:blend_mode". |
![]() | GetInstanceId | Returns the object's unique instance ID. This ID can be saved in EncodedObjectAsID, and can be used to retrieve the object instance with @GDScript.instance_from_id. |
![]() | GetMeta | Returns the object's metadata entry for the given name. |
![]() | GetMetaList | Returns the object's metadata as a String. |
![]() | GetMethodList | Returns the object's methods and their signatures as an Array. |
![]() | GetPointCapacity | Returns the capacity of the structure backing the points, useful in conjunction with reserve_space. |
![]() | GetPointConnections | Returns an array with the IDs of the points that form the connection with the given point. var astar = AStar.new() astar.add_point(1, Vector3(0, 0, 0)) astar.add_point(2, Vector3(0, 1, 0)) astar.add_point(3, Vector3(1, 1, 0)) astar.add_point(4, Vector3(2, 0, 0)) astar.connect_points(1, 2, true) astar.connect_points(1, 3, true) var neighbors = astar.get_point_connections(1) # Returns [2, 3] |
![]() | GetPointCount | Returns the number of points currently in the points pool. |
![]() | GetPointPath | |
![]() | GetPointPosition | Returns the position of the point associated with the given id. |
![]() | GetPoints | Returns an array of all points. |
![]() | GetPointWeightScale | Returns the weight scale of the point associated with the given id. |
![]() | GetPropertyList | Returns the object's property list as an Array of dictionaries. Each property's Dictionary contain at least name: String and type: int (see VariantType) entries. Optionally, it can also include hint: int (see PropertyHint), hint_string: String, and usage: int (see PropertyUsageFlags). |
![]() | GetScript | Returns the object's Script instance, or null if none is assigned. |
![]() | GetSignalConnectionList | Returns an Array of connections for the given signal. |
![]() | GetSignalList | Returns the list of signals as an Array of dictionaries. |
![]() | GetType | (Inherited from Object.) |
![]() | HasMeta | Returns true if a metadata entry is found with the given name. |
![]() | HasMethod | Returns true if the object contains the given method. |
![]() | HasPoint | Returns whether a point associated with the given id exists. |
![]() | HasSignal | Returns true if the given signal exists. |
![]() | HasUserSignal | Returns true if the given user-defined signal exists. Only signals added using AddUserSignal(String, Array) are taken into account. |
![]() | InitRef | Initializes the internal reference counter. Use this only if you really know what you are doing. Returns whether the initialization was successful. |
![]() | IsBlockingSignals | Returns true if signal emission blocking is enabled. |
![]() | IsClass | Returns true if the object inherits from the given class. |
![]() | IsConnected | Returns true if a connection exists for a given signal, target, and method. |
![]() | IsPointDisabled | Returns whether a point is disabled or not for pathfinding. By default, all points are enabled. |
![]() | IsQueuedForDeletion | Returns true if the QueueFree method was called for the object. |
![]() | MemberwiseClone | (Inherited from Object.) |
![]() | Notification | Send a given notification to the object, which will also trigger a call to the _Notification(Int32) method of all classes that the object inherits from. If reversed is true, _Notification(Int32) is called first on the object's own class, and then up to its successive parent classes. If reversed is false, _Notification(Int32) is called first on the highest ancestor (Object itself), and then down to its successive inheriting classes. |
![]() | PropertyListChangedNotify | Notify the editor that the property list has changed, so that editor plugins can take the new values into account. Does nothing on export builds. |
![]() | Reference_ | Increments the internal reference counter. Use this only if you really know what you are doing. Returns true if the increment was successful, false otherwise. |
![]() | RemoveMeta | Removes a given entry from the object's metadata. See also SetMeta(String, Object). |
![]() | RemovePoint | Removes the point associated with the given id from the points pool. |
![]() | ReserveSpace | Reserves space internally for num_nodes points, useful if you're adding a known large number of points at once, for a grid for instance. New capacity must be greater or equals to old capacity. |
![]() | Set | Assigns a new value to the given property. If the property does not exist, nothing will happen. Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase). |
![]() | SetBlockSignals | If set to true, signal emission is blocked. |
![]() | SetDeferred | Assigns a new value to the given property, after the current frame's physics step. This is equivalent to calling Set(String, Object) via CallDeferred(String, Object), i.e. call_deferred("set", property, value). Note: In C#, the property name must be specified as snake_case if it is defined by a built-in Godot node. This doesn't apply to user-defined properties where you should use the same convention as in the C# source (typically PascalCase). |
![]() | SetIndexed | Assigns a new value to the property identified by the NodePath. The node path should be relative to the current object and can use the colon character (:) to access nested properties. Example: set_indexed("position", Vector2(42, 0)) set_indexed("position:y", -10) print(position) # (42, -10) |
![]() | SetMessageTranslation | Defines whether the object can translate strings (with calls to Tr(String)). Enabled by default. |
![]() | SetMeta | Adds, changes or removes a given entry in the object's metadata. Metadata are serialized and can take any Variant value. To remove a given entry from the object's metadata, use RemoveMeta(String). Metadata is also removed if its value is set to null. This means you can also use set_meta("name", null) to remove metadata for "name". |
![]() | SetPointDisabled | Disables or enables the specified point for pathfinding. Useful for making a temporary obstacle. |
![]() | SetPointPosition | Sets the position for the point with the given id. |
![]() | SetPointWeightScale | Sets the weight_scale for the point with the given id. The weight_scale is multiplied by the result of _ComputeCost(Int32, Int32) when determining the overall cost of traveling across a segment from a neighboring point to this point. |
![]() | SetScript | Assigns a script to the object. Each object can have a single script assigned to it, which are used to extend its functionality. If the object already had a script, the previous script instance will be freed and its variables and state will be lost. The new script's method will be called. |
![]() ![]() | ToSignal |
Returns a new SignalAwaiter awaiter configured to complete when the instance
source emits the signal specified by the signal parameter.
(Inherited from Object.) |
![]() | ToString | (Inherited from Object.) |
![]() | Tr | Translates a message using translation catalogs configured in the Project Settings. Only works if message translation is enabled (which it is by default), otherwise it returns the message unchanged. See SetMessageTranslation(Boolean). |
![]() | Unreference | Decrements the internal reference counter. Use this only if you really know what you are doing. Returns true if the decrement was successful, false otherwise. |