player.gd 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. extends CharacterBody2D
  2. @onready var sprite := $Sprite2D
  3. var gravity: int = ProjectSettings.get_setting("physics/2d/default_gravity")
  4. const base_move_speed : int = 160
  5. const overhead_jump_height : int = 4
  6. const base_jump_height : int = 64
  7. var move_speed : float
  8. var jump_height : float
  9. var jump_velocity : float
  10. var coin_count
  11. var is_absolutely_gold : bool = false
  12. func _ready() -> void:
  13. set_coin_count(0)
  14. func collect_coin() -> void:
  15. set_coin_count(coin_count + 1)
  16. if coin_count == 5:
  17. is_absolutely_gold = true
  18. velocity.x = 0
  19. EventBus.player_goldened.emit()
  20. func set_coin_count(value: int) -> void:
  21. coin_count = value
  22. jump_height = base_jump_height - 16 * coin_count
  23. # h = (v^2 - v0^2)/2g
  24. jump_velocity = -sqrt((jump_height + overhead_jump_height) * 2 * gravity)
  25. move_speed = base_move_speed - 10 * coin_count
  26. sprite.frame_coords.y = value
  27. func _physics_process(delta: float) -> void:
  28. # Add the gravity.
  29. if not is_on_floor():
  30. velocity.y += gravity * delta
  31. if is_absolutely_gold:
  32. move_and_slide()
  33. return
  34. # Handle Jump.
  35. if Input.is_action_just_pressed("player_jump") and is_on_floor():
  36. velocity.y = jump_velocity
  37. # Get the input direction and handle the movement/deceleration.
  38. var direction := Input.get_axis("player_left", "player_right")
  39. if direction:
  40. velocity.x = direction * move_speed
  41. else:
  42. velocity.x = move_toward(velocity.x, 0, move_speed)
  43. if direction > 0:
  44. sprite.frame_coords.x = 0
  45. elif direction < 0:
  46. sprite.frame_coords.x = 1
  47. move_and_slide()