player.gd 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. class_name Player
  2. extends KinematicBody2D
  3. # Keep this in sync with the AnimationTree's state names and numbers.
  4. enum States {
  5. IDLE = 0,
  6. WALK = 1,
  7. RUN = 2,
  8. FLY = 3,
  9. FALL = 4,
  10. }
  11. var speed = Vector2(120.0, 360.0)
  12. var velocity = Vector2.ZERO
  13. var falling_slow = false
  14. var falling_fast = false
  15. var no_move_horizontal_time = 0.0
  16. onready var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")
  17. onready var sprite = $Sprite
  18. onready var sprite_scale = sprite.scale.x
  19. func _ready():
  20. $AnimationTree.active = true
  21. func _physics_process(delta):
  22. velocity.y += gravity * delta
  23. if no_move_horizontal_time > 0.0:
  24. # After doing a hard fall, don't move for a short time.
  25. velocity.x = 0.0
  26. no_move_horizontal_time -= delta
  27. else:
  28. velocity.x = (Input.get_action_strength("move_right") - Input.get_action_strength("move_left")) * speed.x
  29. if Input.is_action_pressed("walk"):
  30. velocity.x *= 0.2
  31. #warning-ignore:return_value_discarded
  32. velocity = move_and_slide(velocity, Vector2.UP)
  33. # Calculate flipping and falling speed for animation purposes.
  34. if velocity.x > 0:
  35. sprite.transform.x = Vector2(sprite_scale, 0)
  36. elif velocity.x < 0:
  37. sprite.transform.x = Vector2(-sprite_scale, 0)
  38. if velocity.y > 500:
  39. falling_fast = true
  40. falling_slow = false
  41. elif velocity.y > 300:
  42. falling_slow = true
  43. # Check if on floor and do mostly animation stuff based on it.
  44. if is_on_floor():
  45. if falling_fast:
  46. $AnimationTree["parameters/land_hard/active"] = true
  47. no_move_horizontal_time = 0.4
  48. falling_fast = false
  49. elif falling_slow:
  50. $AnimationTree["parameters/land/active"] = true
  51. falling_slow = false
  52. if Input.is_action_just_pressed("jump"):
  53. $AnimationTree["parameters/jump/active"] = true
  54. velocity.y = -speed.y
  55. if abs(velocity.x) > 50:
  56. $AnimationTree["parameters/state/current"] = States.RUN
  57. $AnimationTree["parameters/run_timescale/scale"] = abs(velocity.x) / 60
  58. elif velocity.x:
  59. $AnimationTree["parameters/state/current"] = States.WALK
  60. $AnimationTree["parameters/walk_timescale/scale"] = abs(velocity.x) / 12
  61. else:
  62. $AnimationTree["parameters/state/current"] = States.IDLE
  63. else:
  64. if velocity.y > 0:
  65. $AnimationTree["parameters/state/current"] = States.FALL
  66. else:
  67. $AnimationTree["parameters/state/current"] = States.FLY