Advertisement
Bwag35

Character movement and animations

Apr 27th, 2024
1,074
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
GDScript 1.16 KB | Gaming | 0 0
  1. extends CharacterBody2D
  2.  
  3.  
  4. const SPEED = 300.0
  5. const JUMP_VELOCITY = -400.0
  6.  
  7. @onready var animation_player = $AnimationPlayer
  8.  
  9. @onready var sprite = $Sprite2D
  10.  
  11.  
  12. var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
  13.  
  14.  
  15. func _physics_process(delta):
  16.  
  17.     if not is_on_floor():
  18.         velocity.y += gravity * delta
  19.  
  20.    
  21.     if Input.is_action_just_pressed("jump") and is_on_floor():
  22.         velocity.y = JUMP_VELOCITY
  23.  
  24.  
  25.     var direction = Input.get_axis("left", "right")
  26.     if direction:
  27.         velocity.x = direction * SPEED
  28.     else:
  29.         velocity.x = move_toward(velocity.x, 0, SPEED)
  30.    
  31.     if direction != 0:
  32.         switch_direction(direction)
  33.        
  34.    
  35.     move_and_slide()
  36.     update_animations(direction)
  37. func update_animations(direction):
  38.     if is_on_floor() and velocity.x == 0 :
  39.         animation_player.play('Idle')
  40.     else:
  41.         animation_player.play('run')
  42.     if velocity.y < 0:
  43.         animation_player.play('jump')
  44.     if velocity.y > 0:
  45.         animation_player.play('fall')
  46.    
  47. func switch_direction(direction):
  48.     sprite.flip_h = (direction == -1)
  49.     sprite.position.x = direction * 6
  50.  
  51.  
  52.  
  53. func _process(delta):
  54.     if Input.is_action_just_pressed('Attack'):
  55.         animation_player.play('swing_nomove')
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement