-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pathfinding.gd
83 lines (59 loc) · 2.05 KB
/
Pathfinding.gd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
extends Node2D
class_name Pathfinding
var astar = AStar2D.new()
export (NodePath) onready var ground = get_node(ground)
var tilemap: TileMap
var half_cell_size: Vector2
var used_rect:Rect2
func _ready():
create_navigation_map(ground)
func update_navigation_map():
for point in astar.get_points():
astar.set_point_disabled(point, false)
var obstacles = get_tree().get_nodes_in_group("Obstacles");
for obstacle in obstacles:
if obstacle is TileMap:
var tiles = obstacle.get_used_cells()
for tile in tiles:
var id = get_id_for_point(tile)
if astar.has_point(id):
astar.set_point_disabled(id, true)
func create_navigation_map(tilemap: TileMap):
self.tilemap =tilemap
half_cell_size = tilemap.cell_size / 2
used_rect = tilemap.get_used_rect()
var tiles = tilemap.get_used_cells()
add_traversable_tiles(tiles)
connect_traversable_tiles(tiles)
func add_traversable_tiles(tiles: Array):
for tile in tiles:
var id = get_id_for_point(tile)
astar.add_point(id, tile)
func connect_traversable_tiles(tiles: Array):
for tile in tiles:
var id = get_id_for_point(tile)
for x in 3:
for y in 3:
var target = tile + Vector2(x-1, y-1)
var target_id = get_id_for_point(target)
if tile == target || not astar.has_point(target_id):
continue
astar.connect_points(id, target_id, true)
func get_id_for_point(point: Vector2):
var x = point.x - used_rect.position.x
var y = point.y - used_rect.position.y
return x + y * used_rect.size.x
#start and end are in global_position
func get_new_path(start: Vector2, end: Vector2) -> Array:
var start_tile = tilemap.world_to_map(start)
var end_tile = tilemap.world_to_map(end)
var start_id = get_id_for_point(start_tile)
var end_id = get_id_for_point(end_tile)
if not astar.has_point(start_id) or not astar.has_point(end_id):
return []
var path_map = astar.get_point_path(start_id, end_id)
var path_world = []
for point in path_map:
var point_world = tilemap.map_to_world(point) + half_cell_size
path_world.append(point_world)
return path_world