player.gd 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. extends CharacterBody2D
  2. const WALK_FORCE = 600
  3. const WALK_MAX_SPEED = 200
  4. const STOP_FORCE = 1300
  5. const JUMP_SPEED = 200
  6. @onready var gravity: float = ProjectSettings.get_setting("physics/2d/default_gravity")
  7. func _physics_process(delta: float) -> void:
  8. # Horizontal movement code. First, get the player's input.
  9. var walk := WALK_FORCE * (Input.get_axis(&"move_left", &"move_right"))
  10. # Slow down the player if they're not trying to move.
  11. if abs(walk) < WALK_FORCE * 0.2:
  12. # The velocity, slowed down a bit, and then reassigned.
  13. velocity.x = move_toward(velocity.x, 0, STOP_FORCE * delta)
  14. else:
  15. velocity.x += walk * delta
  16. # Clamp to the maximum horizontal movement speed.
  17. velocity.x = clamp(velocity.x, -WALK_MAX_SPEED, WALK_MAX_SPEED)
  18. # Vertical movement code. Apply gravity.
  19. velocity.y += gravity * delta
  20. # Move based on the velocity and snap to the ground.
  21. # TODO: This information should be set to the CharacterBody properties instead of arguments: snap, Vector2.DOWN, Vector2.UP
  22. # TODO: Rename velocity to linear_velocity in the rest of the script.
  23. move_and_slide()
  24. # Check for jumping. is_on_floor() must be called after movement code.
  25. if is_on_floor() and Input.is_action_just_pressed(&"jump"):
  26. velocity.y = -JUMP_SPEED