Godot Version
4.6.1
Question
Hello
I was following tutorial above and recreated every step, expect the map, which I replaced with simple single TileMapLayer.
When I tried to test it, i got “Invalid assignment of property or key ‘global_position’ with value of type ‘Vector2’ on a base object of type ‘Nil’.” error.
In test run, player can move normally, but enemy doesn’t do anything and Line2D also doesn’t shows up
I found info that this problem may come from global position not being set, but I don’t understand this enogh to solve it
Here is Player’s code:
extends CharacterBody2D
const tile_size = 128
signal player_did_a_move
func _process(delta: float) -> void:
if Input.is_action_just_pressed("up"):
global_position.y -= tile_size
emit_signal("player_did_a_move")
elif Input.is_action_just_pressed("down"):
global_position.y += tile_size
emit_signal("player_did_a_move")
elif Input.is_action_just_pressed("right"):
global_position.x += tile_size
emit_signal("player_did_a_move")
elif Input.is_action_just_pressed("left"):
global_position.x -= tile_size
emit_signal("player_did_a_move")
And here is Enemy’s code:
extends CharacterBody2D
const TILE_SIZE = 128
const TURN_TO_MOVE: int = 2
@export var tilemap_layer_node: TileMapLayer = null
@export var player_node: CharacterBody2D = null
@export var visual_path_line2D: Line2D = null
var pathfinding_grid: AStarGrid2D = AStarGrid2D.new()
var path_to_player: Array =
var turn_counter: int = 1
func _ready() → void:
visual_path_line2D.global_position = Vector2(TILE_SIZE/2.0, TILE_SIZE/2.0)
player_node.player_did_a_move.connect(_move_ai)
pathfinding_grid.region = tilemap_layer_node.get_used_rect()
pathfinding_grid.cell_size = Vector2(TILE_SIZE, TILE_SIZE)
pathfinding_grid.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
pathfinding_grid.update()
for cell in tilemap_layer_node.get_used_cells():
pathfinding_grid.set_point_solid(cell, true)
_move_ai()
func _move_ai():
path_to_player = pathfinding_grid.get_point_path(global_position / TILE_SIZE, player_node.global_position / TILE_SIZE)
visual_path_line2D.points = path_to_player
if turn_counter != TURN_TO_MOVE:
turn_counter += 1
else:
if path_to_player.size() > 1:
path_to_player.remove_at(0)
var go_to_pos: Vector2 = path_to_player[0] * Vector2(TILE_SIZE/2.0, TILE_SIZE/2.0)
if go_to_pos.x != global_position.x:
$Enemy1Sprite2D.flip_h = false if go_to_pos.x > global_position.x else true
global_position = go_to_pos
visual_path_line2D.points = path_to_player


