Advertisement
ersignee_

Movement Script

Apr 6th, 2023 (edited)
866
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
GDScript 1.02 KB | Source Code | 0 0
  1. extends CharacterBody2D
  2.  
  3. const SPEED = 120.0
  4.  
  5. func _physics_process(delta):
  6.     #input & animations handling
  7.     var movement = Vector2()
  8.     movement.x = Input.get_axis("left","right")
  9.     movement.y = Input.get_axis("up","down")
  10.     movement = movement.normalized()
  11.     if movement != Vector2.ZERO:
  12.         $RayCast2D.target_position = movement * 32
  13.     velocity = movement * SPEED
  14.     update_animation(movement)
  15.     move_and_slide()
  16.  
  17. func get_direction_as_string():
  18.     #converting vector to string to simplify the update_animation() function
  19.     var dir = $RayCast2D.target_position
  20.     if dir.x > 0:
  21.         return "right"
  22.     elif dir.x < 0:
  23.         return "left"
  24.     elif dir.y > 0:
  25.         return "up"
  26.     elif dir.y < 0:
  27.         return "down"
  28.  
  29. func update_animation(movement):
  30.     #switching UP/DOWN to play "run_right" animation
  31.     var dir = get_direction_as_string()
  32.     if dir == "up" or dir == "down":
  33.         dir = "right"
  34.     #update sprite animation based on movement direction
  35.     if movement != Vector2.ZERO:
  36.         $AnimatedSprite2D.play("run_"+dir)
  37.     else:
  38.         $AnimatedSprite2D.play("idle")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement