Has anyone figured out how to do a top-down animation cycle while moving a character with mouse clicks? I took the example from https://docs.godotengine.org/en/3.1/tutorials/2d/2d_movement.html#rotation-movement

With the script below, I succeeded with a two-way animation cycle. Left and Right animations work, but I am having a hard time calculating a logic to have four-way animation cycle to work.

``````extends KinematicBody2D

export (int) var speed = 200

var target = Vector2()
var velocity = Vector2()

func _input(event):
if event.is_action_pressed('click'):
target = get_global_mouse_position()

func _physics_process(delta):
velocity = (target - position).normalized() * speed

# run animation cycles
# these won't work

if position.y > target.y:
\$AnimationPlayer.play('walk_down')
if position.y < target.y:
\$AnimationPlayer.play('walk_up')

# these will run fine
if position.x < target.x:
\$AnimationPlayer.play('walk_right')
if position.x > target.x:
\$AnimationPlayer.play('walk_left')

if velocity == Vector2(0,0):
\$AnimationPlayer.play('idle')

if (target - position).length() > 5:
move_and_slide(velocity)
``````
in Engine

man, i'm just a beginning, but u helped me and i think i can help u too.
thats not perfect, but it worked for me:

``````func _physics_process(_delta):

if Input.is_action_pressed("click"):
target = get_global_mouse_position()

velocity = (target-position).normalized()*speed
#rotation = velocity.angle()

if (target - position).length() > 2:
velocity = move_and_slide(velocity)
if position.y > target.y:
if (position.x-target.x)>(position.y-target.y):
\$sprite_move.play("mov_left")
else:
\$sprite_move.play("mov_up")
if position.y < target.y:
if (position.x-target.x)<(position.y-target.y):
\$sprite_move.play("mov_right")
else:
\$sprite_move.play("mov_down")

else:
\$sprite_move.stop()
``````

check this and let me know

by (18 points)

got even better:

``````if (target - position).length() > 2:
velocity = move_and_slide(velocity)

if abs(position.x-target.x)<abs(position.y-target.y):
if position.y < target.y:
\$sprite_move.play("mov_down")
else:
\$sprite_move.play("mov_up")
if abs(position.x-target.x)>abs(position.y-target.y):
if position.x < target.x:
\$sprite_move.play("mov_right")
else:
\$sprite_move.play("mov_left")

else:
\$sprite_move.stop()
``````

i understod the script needed a order of priority to check, if more of one answers get a true valor, the moviment fail, because the engine cant choose wat true value to use. so i made the script chek the bigger distance between the position and target, if in the X or in the y. so that worked fine. check in your project.