- Edited
I have a 9x9 board
I want to implement the enemy movement on the board, I have the angle to the target (player),
What algorithm/formula can I use to find the next tile to move the enemy (AI) to?
I have a 9x9 board
I want to implement the enemy movement on the board, I have the angle to the target (player),
What algorithm/formula can I use to find the next tile to move the enemy (AI) to?
Welcome to the forums @venatus!
If you have an angle, I would just convert it to a direction vector using cos
and sin
and then clamp that to the nearest direction. Something like this:
# I'll assume the angle is in a variable called target_angle
var target_dir = Vector2(cos(target_angle), sin(target_angle))
# The direction to move the AI towards
var direction = null
# I'm just using a bunch of IF statements here, but there is probably better ways to do this
# First, figure out which axis is strongest. The highest value on the axis means we will move
# in that direction (assuming its impossible to move diagonally)
# We'll do this by seeing if the absolute X value is higher than the absolute Y
if (abs(target_dir.x) >= abs(target_dir.y)):
# If true, then we know we're moving either left or right. We can figure out
# which using the sign (negative = left, positive = right)
if (target_dir.x > 0):
direction = "left"
else:
direction = "right"
# If the Y value is greater than the X value, then we're moving horizontally
else:
# We need to know if we're moving up or down (up = negative, down = positive)
if (target_dir.y > 0):
direction = "up"
else:
direction = "down"
# Then we can use the direction calculated to move the AI
move_ai_towards_direction(direction)
The left/right and up/down signs may be out of order, so you may need to experiment with it, but hopefully the code above gives an idea on how to find the direction needed to move the AI relative to the target angle.
on your Tilemap node, in the tilemap resource, give your tiles a navigation box, then have the enemy reference that tilemap node and use get_simple_path(), it will return a list of world coordinates. Use the enemies grid position and the players grid position in the parameters and set the optimize param to false to get a tile by tile path.
Thanks @TwistedTwigleg You solution seems to work well.
@batomow I tried this solution at the beginning but couldn't get the simple path out of the tilemap, I know how to use the navigation system in Godot when using Navigation2D, but not when the navigation is set per tile, if you have any idea it will help. Thanks.