game-developmentgodotgodot4

How to detect movement for CharacterBody2D?


I am trying to create a 2D game with controls similar to Dota or LoL, and I am struggling with changing animations depending on if my character is moving or not

I tried this code in the movement script:

if position.distance_to(click_pos) > 2:
    $AnimatedSprite2D.set_animation("run")
    target_pos = (click_pos - position).normalized()
    velocity = target_pos * speed
    move_and_slide()
else:
    $AnimatedSprite2D.set_animation("idle")

However it keeps returning the error:

Attempt to call function 'set_animation' in base 'null instance' on a null instance

I also tried this in a separate script:

if Movement.target_pos != Movement.position:
    set_animation("run")
if  Movement.velocity == Vector2(0, 0): 
    set_animation("idle")

But it doesn't run the idle animation at all.

!!!PLEASE HELP!!!


Solution

  • I think it might work better if you do $AnimatedSprite2D.play("idle) instead

    Ex:

    if position.distance_to(click_pos) > 2:
      $AnimatedSprite2D.play("run")
      target_pos = (click_pos - position).normalized()
      velocity = target_pos * speed
      move_and_slide()
    else:
      $AnimatedSprite2D.play("idle")
    

    Also make sure you have looping on if you want the animation to repeat itself. Hope this helps!