Godot Version
4.3
Question
I am experimenting with a hex-based game, and specifically trying to find a simple way to move the player around the grid. Bearing in mind my “game” at the moment is just a bare-bones testbed, what I’m trying to do is get it so that when the space bar is held down, a selection hex appears that can then be moved around using the keyboard. When the player releases the space bar, the player moves to whatever tile the selection hex was on when the space bar was released.
game.gd
:
extends Node2D
@onready var tile_map: TileMapLayer = $TileMapLayer
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
var player_scene = preload("res://scenes/player.tscn")
var player_instance = player_scene.instantiate()
add_child(player_instance)
player_instance.set_global_position(tile_map.map_to_local(Vector2i(6,3)))
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
pass
Right now all I’m doing is spawning in the player.tscn
, since later I will want the ability to put the player where I want, and not necessarily where they were put at game creation. That’s essentially all game.gd
does at this point. You can even see the default process function at the bottom.
player.gd
:
extends CharacterBody2D
@onready var tile_map: TileMapLayer = $TileMapLayer
var selector = preload("res://scenes/selection.tscn")
var selector_instance = selector.instantiate()
var start_position
var end_position
func _input(event: InputEvent) -> void:
if event.is_action_pressed("movement_hold"):
var tween = create_tween()
add_child(selector_instance)
if Input.is_action_just_pressed("select_up"):
pass
if event.is_action_released("movement_hold"):
remove_child(selector_instance)
Here is where I’m having issues. selection.tscn
is nothing more than a bare bones Sprite2D
to give a visual aid to the player. It spawns on top of the player when the spacebar is held, and disappears when the spacebar is released. So far so good(?)
I want the ability to move the selector around, but I’m having trouble figuring out how to access the location of… anything. I’d like to just work with the tilemap coordinates, but I can’t figure out how to tell the selector to “move up one hex.” Most of the functions I’ve found (like map_to_local
) require the Vector2D
coordinates, rather than returning them. The tricky part seems to be the fact that player.tscn
doesn’t exist until the game starts, so it’s not intuitive to me how to reference it. Something related to get_tree
?
The idea is to eventually use cell_neighbor_top_side
et all to specifically send the selector to the surrounding cells based on the inputs, but I need to be able to tell the code “this is your origin cell” in order to get those destinations
Thanks in advance!