characterbody_controller.gd 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. extends CharacterBody2D
  2. var _initial_velocity = Vector2.ZERO
  3. var _constant_velocity = Vector2.ZERO
  4. var _motion_speed = 400.0
  5. var _gravity_force = 50.0
  6. var _jump_force = 1000.0
  7. var _velocity = Vector2.ZERO
  8. var _snap = 0.0
  9. var _floor_max_angle = 45.0
  10. var _stop_on_slope = false
  11. var _move_on_floor_only = false
  12. var _constant_speed = false
  13. var _jumping = false
  14. var _keep_velocity = false
  15. func _physics_process(_delta):
  16. if _initial_velocity != Vector2.ZERO:
  17. _velocity = _initial_velocity
  18. _initial_velocity = Vector2.ZERO
  19. _keep_velocity = true
  20. elif _constant_velocity != Vector2.ZERO:
  21. _velocity = _constant_velocity
  22. elif not _keep_velocity:
  23. _velocity.x = 0.0
  24. # Handle horizontal controls.
  25. if Input.is_action_pressed(&"character_left"):
  26. if position.x > 0.0:
  27. _velocity.x = -_motion_speed
  28. _keep_velocity = false
  29. _constant_velocity = Vector2.ZERO
  30. elif Input.is_action_pressed(&"character_right"):
  31. if position.x < 1024.0:
  32. _velocity.x = _motion_speed
  33. _keep_velocity = false
  34. _constant_velocity = Vector2.ZERO
  35. # Handle jump controls and gravity.
  36. if is_on_floor():
  37. if not _jumping and Input.is_action_just_pressed(&"character_jump"):
  38. # Start jumping.
  39. _jumping = true
  40. _velocity.y = -_jump_force
  41. else:
  42. _velocity.y += _gravity_force
  43. floor_snap_length = _snap
  44. floor_stop_on_slope = _stop_on_slope
  45. floor_block_on_wall = _move_on_floor_only
  46. floor_constant_speed = _constant_speed
  47. floor_max_angle = deg_to_rad(_floor_max_angle)
  48. velocity = _velocity
  49. move_and_slide()
  50. _velocity = velocity
  51. # Get next jump ready.
  52. if _jumping:
  53. _jumping = false