Godot Version
4.3
Question
I’m trying to create a creature that always follows the player with pathfinding, and I’ve already managed to add the pathfinding to a target position, however im not sure how to dynamically change the target position (vector2i) to the players position. Currently the pathfinding works on an Astar Algorithm using a TileMapLayer where i have to input a target position in the code (tile_map_layer.gd). If someone could help me either find the vector2i of the player and store it in a variable or find the coordinates of what tile the player is in and store it in a variable, that would be great.
tile_map_layer.gd: (main code)
extends TileMapLayer
var astargrid = AStarGrid2D.new()
const main_layer = 0
const main_source = 0
const path_taken_atlas_coords = Vector2i(0,1)
const is_solid = "is_solid"
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
setup_grid()
show_path()
func setup_grid():
#how big of a region i want the pathfinder to comprehend kinda idk. set to 1 bigger than needed for some
#reason or maybe i counted wrong idk. first 0,0 i forgot what they do. wait nvm i remember they
#are where the top left corner of the region starts
astargrid.region = Rect2i(0, 0, 25, 15)
astargrid.cell_size = Vector2i(64, 64)
astargrid.default_compute_heuristic = AStarGrid2D.HEURISTIC_EUCLIDEAN
astargrid.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_ONLY_IF_NO_OBSTACLES
astargrid.update()
for cell in get_used_cells():
astargrid.set_point_solid(cell, is_spot_solid(cell), )
astargrid.update()
#so the first vector2i in the next line to start pos, and the last one to end pos
func show_path():
var path_taken = astargrid.get_id_path(Vector2i(1,1), Vector2i(4, 8))
for cell in path_taken:
set_cell(cell, main_source, path_taken_atlas_coords)
await get_tree().create_timer(.1).timeout
func is_spot_solid(spot_to_check:Vector2i) -> bool:
return get_cell_tile_data(spot_to_check).get_custom_data(is_solid)
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(_delta: float) -> void:
pass
Character_body_2d.gd: (attached to player)
extends CharacterBody2D
const SPEED = 200.0
const JUMP_VELOCITY = -400.0
func _physics_process(delta: float) -> void:
# Add the gravity.
if not is_on_floor():
velocity += get_gravity() * delta
# Handle jump.
if Input.is_action_just_pressed("space") and is_on_floor():
velocity.y = JUMP_VELOCITY
# Get the input direction and handle the movement/deceleration.
# As good practice, you should replace UI actions with custom gameplay actions.
var direction := Input.get_axis("a", "d")
if direction:
velocity.x = direction * SPEED
else:
velocity.x = move_toward(velocity.x, 0, SPEED)
move_and_slide()
ignore my notes i have no idea what im doing