I was wondering how could it be achieved on character bodies 2d not controlled by the player without having to make it tilebased. Especially if npc is moving toward a destination. Only up, down, left, right. Any ideas?
One way to do it is to use astar pathfinding. You have to use a grid but it can just be mathematical. You can set astar to either use diagonals or not. The path points it returns will always be vertical or horizontal.
Thanks for your reply. I didn’t want to use astar pathfinding because I didn’t want the movement to relay on a grid.
I did manage to get the npc moving in only four directions but I had a problem when the player stands diagonally to the npc, the npc would just freak out between the two closest directions and then move diagonally. After some fiddling, the solution was simply to add a direction tolerance value. Here is the code for anyone who finds this thread:
var _direction : Vector2
var direction_tolerance: float = 10.0
func _physics_process(_delta):
var distance = target.global_position - global_position
if abs(distance.x) > abs(distance.y) + direction_tolerance:
if distance.x > 0:
_direction.x = 1 # Move right
else:
_direction.x = -1 # Move left
elif abs(distance.y) > abs(distance.x) + direction_tolerance:
if distance.y > 0:
_direction.y = 1 # Move down
else:
_direction.y = -1 # Move up
_direction = _direction.normalized()
velocity = _direction * move_speed
move_and_slide()
and don’t forget to change the way your sprite is facing depending on the direction.