AStar

Inherits: Reference < Object

An implementation of A* to find the shortest paths among connected points in space.

Descripción

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 add_point and create segments manually with connect_points. Then you can test if there is a path between two points with the are_points_connected function, get a path containing indices by get_id_path, or one containing actual coordinates with get_point_path.

It is also possible to use non-Euclidean distances. To do so, create a class that extends AStar and override methods _compute_cost and _estimate_cost. 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)

_estimate_cost 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 _estimate_cost return the same value as _compute_cost to provide the algorithm with the most accurate information.

If the default _estimate_cost and _compute_cost methods are used, or if the supplied _estimate_cost 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 the sum of the _compute_cost results of all segments in the path multiplied by the weight_scales of the endpoints 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 the sum of Euclidean distances of all segments in the path.

Métodos

float

_compute_cost ( int from_id, int to_id ) virtual

float

_estimate_cost ( int from_id, int to_id ) virtual

void

add_point ( int id, Vector3 position, float weight_scale=1.0 )

bool

are_points_connected ( int id, int to_id, bool bidirectional=true ) const

void

clear ( )

void

connect_points ( int id, int to_id, bool bidirectional=true )

void

disconnect_points ( int id, int to_id, bool bidirectional=true )

int

get_available_point_id ( ) const

int

get_closest_point ( Vector3 to_position, bool include_disabled=false ) const

Vector3

get_closest_position_in_segment ( Vector3 to_position ) const

PoolIntArray

get_id_path ( int from_id, int to_id )

int

get_point_capacity ( ) const

PoolIntArray

get_point_connections ( int id )

int

get_point_count ( ) const

PoolVector3Array

get_point_path ( int from_id, int to_id )

Vector3

get_point_position ( int id ) const

float

get_point_weight_scale ( int id ) const

Array

get_points ( )

bool

has_point ( int id ) const

bool

is_point_disabled ( int id ) const

void

remove_point ( int id )

void

reserve_space ( int num_nodes )

void

set_point_disabled ( int id, bool disabled=true )

void

set_point_position ( int id, Vector3 position )

void

set_point_weight_scale ( int id, float weight_scale )

Descripciones de Métodos

  • float _compute_cost ( int from_id, int to_id ) virtual

Llamado cuando se calcula el coste entre dos puntos conectados.

Nota que esta funcion esta oculta en la clase AStar por defecto.


  • float _estimate_cost ( int from_id, int to_id ) virtual

Llamado cuando se estima el coste entre un punto y la ruta del punto final.

Nota que esta funcion esta oculto en la clase AStar por defecto.


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 _compute_cost 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.


  • bool are_points_connected ( int id, int to_id, bool bidirectional=true ) const

Devuelve si dos puntos dados estan directamente conectados por un segmento. Si bidirectional es false, devuelve si el movimiento desde id a to_id es posible a traves del segmento.


  • void clear ( )

Limpia todos los puntos y segmentos.


  • void connect_points ( int id, int to_id, bool bidirectional=true )

Crea un segmento entre los puntos dados. Si bidirectional es false, solo el movimiento desde id a to_id es permitido, no la direccion inversa.

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)

  • void disconnect_points ( int id, int to_id, bool bidirectional=true )

Elimina el segmento entre los puntos dados. Si bidirectional es false, solo el movimiento desde id a to_id es prevenido, y una segmento unidireccional posiblemente se mantiene.


  • int get_available_point_id ( ) const

Devuelve el punto de Ide proximo disponible con ningun punto asociado a el.


  • int get_closest_point ( Vector3 to_position, bool include_disabled=false ) const

Devuelve el ID del punto mas cercano a to_position, opcionalmente tomando puntos deshabilitados en cuenta. Devuelve -1 si no hay puntos el grupo(pool) de puntos.

Nota: Si varios puntos son los más cercanos a to_position, el pundo con el menor ID será devuelto, asegurando un resultado deterministico.


  • Vector3 get_closest_position_in_segment ( Vector3 to_position ) const

Devuelve la posicion mas cercana a to_position que reside dentro de un segmento entre dos puntos conectados.

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)) # Devuelve (0, 3, 0)

El resultado esta en el segmento que va desde y = 0 a y = 5. Es la posicion mas cercana el segmento de un punto dado.


Devuelve un array con los IDs de los puntos que forman la ruta encontrada por un A estrella entre los puntos dados. El array es ordenado desde el punto de comienzo al punto final de la ruta.

var astar = AStar.new()
astar.add_point(1, Vector3(0, 0, 0))
asta.add_point(2, Vector3(0, 1, 0), 1) # Peso por defecto es 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) # Devuelve [1, 2, 3]

Si tu cambiar el peso del segundo punto a 3, entonces el resultado sera [1, 4, 3], porque ahora aunque la distanica es mayor, es mas facil (menos coste) ir a traves de 4 que a traves del punto 2.


  • int get_point_capacity ( ) const

Devuelve la capacidad de la estructura que respalda los puntos, usado junto con reserve_space.


Devuelve un array con los IDs de los puntos que forman la conneccion con el punto dado.

var astar = AStar.new()
astar.add_point(1, Vector3(0, 0, 0))
astar.add_point(2, Vector1(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 vecinos = astar.get_point_connections() # Devuelve [2, 3]

  • int get_point_count ( ) const

Devuelve el numero de puntos actualmente en el grupo(pool) de puntos.


Returns an array with the points that are in the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path.

Note: This method is not thread-safe. If called from a Thread, it will return an empty PoolVector3Array and will print an error message.


Devuelve la posicion del punto asociado con el id dado.


  • float get_point_weight_scale ( int id ) const

Devuelve el peso del punto asociado con el id dado.


Devuelve un array con todos los puntos.


Devuelve si un punto asociado con el id existe.


  • bool is_point_disabled ( int id ) const

Devuelve si un punto esta deshabilitado or no para el buscador de rutas. Por defecto, todos los puntos estan habilitados.


  • void remove_point ( int id )

Elimina el punto asociado con el id dado del grupo(pool) de puntos.


  • void reserve_space ( int num_nodes )

Espacio de reserva interna para puntos num_nodes, util si tu estas añadiendo un gran numero de puntos a la vez, para un grid por ejemplo. Las nuevas capacidades debes ser mayores o iguales que la anterior capacidad.


  • void set_point_disabled ( int id, bool disabled=true )

Deshabilita o habilita el punto especificado para el buscador de rutas. Util para crear obstaculos temporales.


  • void set_point_position ( int id, Vector3 position )

Coloca la position para el punto con el id dado.


  • void set_point_weight_scale ( int id, float weight_scale )

Sets the weight_scale for the point with the given id. The weight_scale is multiplied by the result of _compute_cost when determining the overall cost of traveling across a segment from a neighboring point to this point.