79 lines
2.5 KiB
GDScript
79 lines
2.5 KiB
GDScript
|
# Script to attach to a node which represents a hex grid
|
||
|
extends Node2D
|
||
|
|
||
|
var HexGrid = preload("./HexGrid.gd").new()
|
||
|
var HexShape = preload("./HexShape.tscn")
|
||
|
|
||
|
onready var highlight = get_node("Highlight")
|
||
|
onready var area_coords = get_node("Highlight/AreaCoords")
|
||
|
onready var hex_coords = get_node("Highlight/HexCoords")
|
||
|
|
||
|
var rect_min = Vector2(-200, 50)
|
||
|
var rect_max = Vector2(400, 200)
|
||
|
|
||
|
var drag_start = null
|
||
|
|
||
|
func _ready():
|
||
|
HexGrid.hex_scale = Vector2(50, 50)
|
||
|
|
||
|
func _draw():
|
||
|
var hex_cell_bb_min = HexGrid.get_hex_at(rect_min).offset_coords
|
||
|
var hex_cell_bb_max = HexGrid.get_hex_at(rect_max).offset_coords
|
||
|
|
||
|
var hex_cell_offset_min = Vector2(
|
||
|
min(hex_cell_bb_min.x, hex_cell_bb_max.x),
|
||
|
min(hex_cell_bb_min.y, hex_cell_bb_max.y)
|
||
|
)
|
||
|
|
||
|
var hex_cell_offset_max = Vector2(
|
||
|
max(hex_cell_bb_min.x, hex_cell_bb_max.x),
|
||
|
max(hex_cell_bb_min.y, hex_cell_bb_max.y)
|
||
|
)
|
||
|
|
||
|
var rect_highlights = get_node ("rect_highlights")
|
||
|
if rect_highlights:
|
||
|
remove_child(rect_highlights)
|
||
|
rect_highlights.queue_free()
|
||
|
|
||
|
rect_highlights = Node2D.new()
|
||
|
rect_highlights.name = "rect_highlights"
|
||
|
add_child(rect_highlights)
|
||
|
|
||
|
for xi in range (hex_cell_offset_min.x, hex_cell_offset_max.x + 1):
|
||
|
for yi in range (hex_cell_offset_min.y, hex_cell_offset_max.y + 1):
|
||
|
var offset_coords = Vector2(xi, yi)
|
||
|
var hex_shape = HexShape.instance()
|
||
|
hex_shape.position = HexGrid.get_hex_center_from_offset(offset_coords)
|
||
|
var hex_shape_coords = hex_shape.get_node("HexCoords")
|
||
|
hex_shape_coords.text = str(offset_coords)
|
||
|
rect_highlights.add_child (hex_shape)
|
||
|
|
||
|
var rect = Rect2(rect_min, rect_max - rect_min)
|
||
|
draw_rect (rect, Color("55FFFFFF"))
|
||
|
|
||
|
|
||
|
func _unhandled_input(event):
|
||
|
if 'position' in event:
|
||
|
var relative_pos = self.transform.affine_inverse() * event.position
|
||
|
# Display the coords used
|
||
|
if area_coords != null:
|
||
|
area_coords.text = str(relative_pos)
|
||
|
if hex_coords != null:
|
||
|
hex_coords.text = str(HexGrid.get_hex_at(relative_pos).axial_coords)
|
||
|
|
||
|
# Snap the highlight to the nearest grid cell
|
||
|
if highlight != null:
|
||
|
highlight.position = HexGrid.get_hex_center(HexGrid.get_hex_at(relative_pos))
|
||
|
|
||
|
if event is InputEventMouseButton:
|
||
|
if event.button_index == BUTTON_LEFT:
|
||
|
if event.pressed:
|
||
|
drag_start = relative_pos
|
||
|
else:
|
||
|
drag_start = null
|
||
|
|
||
|
if drag_start != null:
|
||
|
rect_min = Vector2(min(drag_start.x, relative_pos.x), min(drag_start.y, relative_pos.y))
|
||
|
rect_max = Vector2(max(drag_start.x, relative_pos.x), max(drag_start.y, relative_pos.y))
|
||
|
update()
|