player.gd 1.1 KB

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