GodotComponentTest/scenes/StreamContainer.gd

92 lines
2.6 KiB
GDScript

extends Spatial
onready var hexgrid = preload("res://addons/gdhexgrid/HexGrid.gd").new()
onready var hextile3d = preload("res://scenes/HexTile3D.tscn")
onready var active_tiles = $ActiveTiles
export var world_rect: Rect2 = Rect2() setget set_rect
var offset_coord_rect: Rect2 = Rect2()
var bottom_left_cell: HexCell = HexCell.new()
var top_right_cell: HexCell = HexCell.new()
var tiles = {}
var tiles_by_offset_coord = {}
onready var bounds = $Bounds
func _ready():
set_rect(world_rect)
func is_hex_coord_in_rect (coord: Vector2):
var rect_end = offset_coord_rect.end
return coord.x >= offset_coord_rect.position.x and coord.x < offset_coord_rect.end.x and coord.y >= offset_coord_rect.position.y and coord.y < offset_coord_rect.end.y
func instantiate_hextile3d():
return hextile3d.instance()
func add_hextile_to_tree(hextile3d):
active_tiles.add_child(hextile3d)
func create_hextile3d_at (coord: Vector2) -> HexTile3D:
if not coord in tiles_by_offset_coord.keys():
var new_hextile3d = instantiate_hextile3d()
add_hextile_to_tree(new_hextile3d)
new_hextile3d.game_tile.offset_coords = coord
new_hextile3d.transform.origin.y = -9999
tiles_by_offset_coord[coord] = new_hextile3d
return tiles_by_offset_coord[coord]
func cleanup_tiles():
var num_deleted = 0
var children = active_tiles.get_children()
for child in children:
var tile_offset_coords = child.game_tile.offset_coords
if not is_hex_coord_in_rect(tile_offset_coords):
tiles_by_offset_coord.erase(tile_offset_coords)
child.queue_free()
active_tiles.remove_child(child)
num_deleted = num_deleted + 1
# print ("deleted ", num_deleted, " tiles")
func set_rect(rect: Rect2):
world_rect = rect
if bounds == null:
return
var world_rect_center = rect.get_center()
bounds.transform = Transform(
Vector3 (world_rect.size.x / 2, 0, 0),
Vector3(0, 1, 0), Vector3(0, 0, world_rect.size.y / 2),
Vector3(world_rect_center.x, 0, world_rect_center.y)
)
bottom_left_cell = hexgrid.get_hex_at(Vector2(rect.position.x, rect.end.y))
top_right_cell = hexgrid.get_hex_at(Vector2(rect.end.x, rect.position.y))
offset_coord_rect = Rect2(
bottom_left_cell.offset_coords.x, bottom_left_cell.offset_coords.y,
top_right_cell.offset_coords.x - bottom_left_cell.offset_coords.x, top_right_cell.offset_coords.y - bottom_left_cell.offset_coords.y
)
# print ("----")
# print ("world_rect: ", world_rect)
# print ("cells: ", bottom_left_cell.offset_coords, " to ", top_right_cell.offset_coords)
# print ("offset_coord_rect: ", offset_coord_rect.position, " size: ", offset_coord_rect.size)
cleanup_tiles()
return world_rect