player.gd 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. extends KinematicBody2D
  2. # This demo shows how to build a kinematic controller.
  3. # Member variables
  4. const GRAVITY = 500.0 # pixels/second/second
  5. # Angle in degrees towards either side that the player can consider "floor"
  6. const FLOOR_ANGLE_TOLERANCE = 40
  7. const WALK_FORCE = 600
  8. const WALK_MIN_SPEED = 10
  9. const WALK_MAX_SPEED = 200
  10. const STOP_FORCE = 1300
  11. const JUMP_SPEED = 200
  12. const JUMP_MAX_AIRBORNE_TIME = 0.2
  13. const SLIDE_STOP_VELOCITY = 1.0 # one pixel/second
  14. const SLIDE_STOP_MIN_TRAVEL = 1.0 # one pixel
  15. var velocity = Vector2()
  16. var on_air_time = 100
  17. var jumping = false
  18. var prev_jump_pressed = false
  19. func _physics_process(delta):
  20. # Create forces
  21. var force = Vector2(0, GRAVITY)
  22. var walk_left = Input.is_action_pressed("move_left")
  23. var walk_right = Input.is_action_pressed("move_right")
  24. var jump = Input.is_action_pressed("jump")
  25. var stop = true
  26. if walk_left:
  27. if velocity.x <= WALK_MIN_SPEED and velocity.x > -WALK_MAX_SPEED:
  28. force.x -= WALK_FORCE
  29. stop = false
  30. elif walk_right:
  31. if velocity.x >= -WALK_MIN_SPEED and velocity.x < WALK_MAX_SPEED:
  32. force.x += WALK_FORCE
  33. stop = false
  34. if stop:
  35. var vsign = sign(velocity.x)
  36. var vlen = abs(velocity.x)
  37. vlen -= STOP_FORCE * delta
  38. if vlen < 0:
  39. vlen = 0
  40. velocity.x = vlen * vsign
  41. # Integrate forces to velocity
  42. velocity += force * delta
  43. # Integrate velocity into motion and move
  44. velocity = move_and_slide(velocity, Vector2(0, -1))
  45. if is_on_floor():
  46. on_air_time = 0
  47. if jumping and velocity.y > 0:
  48. # If falling, no longer jumping
  49. jumping = false
  50. if on_air_time < JUMP_MAX_AIRBORNE_TIME and jump and not prev_jump_pressed and not jumping:
  51. # Jump must also be allowed to happen if the character left the floor a little bit ago.
  52. # Makes controls more snappy.
  53. velocity.y = -JUMP_SPEED
  54. jumping = true
  55. on_air_time += delta
  56. prev_jump_pressed = jump