AStar2D

Hereda: RefCounted < Object

Una implementación de A* para encontrar el camino más corto entre dos vértices en un grafo conectado en un espacio 2D.

Descripción

Una implementación del algoritmo A*, utilizado para encontrar el camino más corto entre dos vértices en un grafo conectado en un espacio 2D.

Consulta AStar3D para obtener una explicación más detallada sobre cómo usar esta clase. AStar2D es un envoltorio para AStar3D que aplica coordenadas 2D.

Tutoriales

Propiedades

bool

neighbor_filter_enabled

false

Métodos

float

_compute_cost(from_id: int, to_id: int) virtual const

float

_estimate_cost(from_id: int, end_id: int) virtual const

bool

_filter_neighbor(from_id: int, neighbor_id: int) virtual const

void

add_point(id: int, position: Vector2, weight_scale: float = 1.0)

bool

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

void

clear()

void

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

void

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

int

get_available_point_id() const

int

get_closest_point(to_position: Vector2, include_disabled: bool = false) const

Vector2

get_closest_position_in_segment(to_position: Vector2) const

PackedInt64Array

get_id_path(from_id: int, to_id: int, allow_partial_path: bool = false)

int

get_point_capacity() const

PackedInt64Array

get_point_connections(id: int)

int

get_point_count() const

PackedInt64Array

get_point_ids()

PackedVector2Array

get_point_path(from_id: int, to_id: int, allow_partial_path: bool = false)

Vector2

get_point_position(id: int) const

float

get_point_weight_scale(id: int) const

bool

has_point(id: int) const

bool

is_point_disabled(id: int) const

void

remove_point(id: int)

void

reserve_space(num_nodes: int)

void

set_point_disabled(id: int, disabled: bool = true)

void

set_point_position(id: int, position: Vector2)

void

set_point_weight_scale(id: int, weight_scale: float)


Descripciones de Propiedades

bool neighbor_filter_enabled = false 🔗

  • void set_neighbor_filter_enabled(value: bool)

  • bool is_neighbor_filter_enabled()

Si es true, habilita el filtrado de vecinos a través de _filter_neighbor().


Descripciones de Métodos

float _compute_cost(from_id: int, to_id: int) virtual const 🔗

Llamado al calcular el coste entre dos puntos conectados.

Ten en cuenta que esta función está oculta en la clase AStar2D por defecto.


float _estimate_cost(from_id: int, end_id: int) virtual const 🔗

Se llama cuando se calcula el coste entre un punto y punto final de un trayecto.

Nota que esta función está oculta en la clase AStar2D por defecto.


bool _filter_neighbor(from_id: int, neighbor_id: int) virtual const 🔗

Llamado cuando un vecino entra en el procesamiento y si neighbor_filter_enabled es true. Si se devuelve true, el punto no se procesará.

Ten en cuenta que esta función está oculta en la clase AStar2D por defecto.


void add_point(id: int, position: Vector2, weight_scale: float = 1.0) 🔗

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 0.0 or greater.

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 = AStar2D.new()
astar.add_point(1, Vector2(1, 0), 4) # Adds the point (1, 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(id: int, to_id: int, bidirectional: bool = true) const 🔗

Devuelve si existe una conexión/segmento entre los puntos dados. Si bidirectional es false, devuelve si el movimiento desde id a to_id es posible a través de este segmento.


void clear() 🔗

Limpia todos los puntos y segmentos.


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

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 = AStar2D.new()
astar.add_point(1, Vector2(1, 1))
astar.add_point(2, Vector2(0, 5))
astar.connect_points(1, 2, false)

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

Elimina el segmento entre los puntos dados. Si bidirectional es false, solo el movimiento desde id a to_id se impide, y un segmento unidireccional posiblemente permanece.


int get_available_point_id() const 🔗

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


int get_closest_point(to_position: Vector2, include_disabled: bool = false) const 🔗

Devuelve el ID del punto más cercano a to_position, opcionalmente teniendo en cuenta los puntos desactivados. Devuelve -1 si no hay puntos en el grupo de puntos.

Nota: Si varios puntos son los más cercanos a to_position, se devolverá el que tenga el ID más pequeño, lo que garantiza un resultado determinista.


Vector2 get_closest_position_in_segment(to_position: Vector2) const 🔗

Returns the closest position to to_position that resides inside a segment between two connected points.

var astar = AStar2D.new()
astar.add_point(1, Vector2(0, 0))
astar.add_point(2, Vector2(0, 5))
astar.connect_points(1, 2)
var res = astar.get_closest_position_in_segment(Vector2(3, 3)) # Returns (0, 3)

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.


PackedInt64Array get_id_path(from_id: int, to_id: int, allow_partial_path: bool = false) 🔗

Returns an array with the IDs of the points that form the path found by AStar2D between the given points. The array is ordered from the starting point to the ending point of the path.

If there is no valid path to the target, and allow_partial_path is true, returns a path to the point closest to the target that can be reached.

Note: When allow_partial_path is true and to_id is disabled the search may take an unusually long time to finish.

var astar = AStar2D.new()
astar.add_point(1, Vector2(0, 0))
astar.add_point(2, Vector2(0, 1), 1) # Default weight is 1
astar.add_point(3, Vector2(1, 1))
astar.add_point(4, Vector2(2, 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.


int get_point_capacity() const 🔗

Devuelve la capacidad de la estructura que respalda los puntos, útil en conjunto con reserve_space().


PackedInt64Array get_point_connections(id: int) 🔗

Returns an array with the IDs of the points that form the connection with the given point.

var astar = AStar2D.new()
astar.add_point(1, Vector2(0, 0))
astar.add_point(2, Vector2(0, 1))
astar.add_point(3, Vector2(1, 1))
astar.add_point(4, Vector2(2, 0))

astar.connect_points(1, 2, true)
astar.connect_points(1, 3, true)

var neighbors = astar.get_point_connections(1) # Returns [2, 3]

int get_point_count() const 🔗

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


PackedInt64Array get_point_ids() 🔗

Devuelve un array de todos los ID de los puntos.


PackedVector2Array get_point_path(from_id: int, to_id: int, allow_partial_path: bool = false) 🔗

Devuelve un array con los puntos que están en la ruta encontrada por AStar2D entre los puntos dados. El array se ordena desde el punto de inicio hasta el punto final de la ruta.

Si no hay una ruta válida al destino, y allow_partial_path es true, devuelve una ruta al punto más cercano al destino que se puede alcanzar.

Nota: Este método no es seguro para hilos; solo se puede usar desde un único Thread a la vez. Considera usar Mutex para asegurar el acceso exclusivo a un hilo para evitar condiciones de carrera.

Adicionalmente, cuando allow_partial_path es true y to_id está deshabilitado, la búsqueda puede tardar un tiempo inusualmente largo en finalizar.


Vector2 get_point_position(id: int) const 🔗

Devuelve la posición del punto asociado con el id dado.


float get_point_weight_scale(id: int) const 🔗

Devuelve la escala de peso del punto asociado con el id dado.


bool has_point(id: int) const 🔗

Devuelve si existe un punto asociado con el id dado.


bool is_point_disabled(id: int) const 🔗

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


void remove_point(id: int) 🔗

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


void reserve_space(num_nodes: int) 🔗

Reserva espacio internamente para num_nodes puntos. Útil si vas a añadir un número grande conocido de puntos a la vez, como puntos en una cuadrícula.


void set_point_disabled(id: int, disabled: bool = true) 🔗

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


void set_point_position(id: int, position: Vector2) 🔗

Establece la position para el punto con el id dado.


void set_point_weight_scale(id: int, weight_scale: float) 🔗

Establece el weight_scale para el punto con el id dado. El weight_scale se multiplica por el resultado de _compute_cost() al determinar el coste total de viajar a través de un segmento desde un punto vecino a este punto.