paddle.gd 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. class_name Paddle
  2. extends AnimatableBody2D
  3. ## Follows the player's finger (or mouse) along the bottom of the screen.
  4. enum Width { NORMAL, HALF, DOUBLE }
  5. const SCALE := { Width.NORMAL: 1.0, Width.HALF: 0.5, Width.DOUBLE: 2.0 }
  6. var width := Width.NORMAL
  7. var _screen_width := 0.0
  8. var _shape := RectangleShape2D.new()
  9. @onready var _timer: Timer = $NormalTimer
  10. func _ready() -> void:
  11. _screen_width = get_viewport_rect().size.x
  12. $CollisionShape2D.shape = _shape
  13. _timer.timeout.connect(normal_size)
  14. normal_size()
  15. func _unhandled_input(event: InputEvent) -> void:
  16. if event is InputEventScreenTouch and event.is_pressed():
  17. _move_to((event as InputEventScreenTouch).position.x)
  18. elif event is InputEventScreenDrag:
  19. _move_to((event as InputEventScreenDrag).position.x)
  20. ## Doubles the paddle for a while, or cancels a halving.
  21. func double_size() -> void:
  22. if width == Width.HALF:
  23. normal_size()
  24. return
  25. _set_width(Width.DOUBLE)
  26. _timer.start(Params.POWER_UP_PADDLE_SECONDS)
  27. ## Halves the paddle for a while, or cancels a doubling.
  28. func half_size() -> void:
  29. if width == Width.DOUBLE:
  30. normal_size()
  31. return
  32. _set_width(Width.HALF)
  33. _timer.start(Params.POWER_UP_PADDLE_SECONDS)
  34. func normal_size() -> void:
  35. _timer.stop()
  36. _set_width(Width.NORMAL)
  37. func _set_width(value: Width) -> void:
  38. width = value
  39. _shape.size = Vector2((Params.PADDLE_WIDTH + Params.PADDLE_HEIGHT) * SCALE[width], Params.PADDLE_HEIGHT)
  40. _move_to(position.x)
  41. queue_redraw()
  42. func _move_to(x: float) -> void:
  43. var half: float = Params.PADDLE_WIDTH / 2.0 * SCALE[width]
  44. position.x = clampf(x, half, _screen_width - half)
  45. func _draw() -> void:
  46. var half: float = Params.PADDLE_WIDTH / 2.0 * SCALE[width]
  47. var cap := Params.PADDLE_HEIGHT / 2.0
  48. draw_line(Vector2(-half, 0), Vector2(half, 0), Params.COLOR_GREY, Params.PADDLE_HEIGHT)
  49. draw_circle(Vector2(-half, 0), cap, Params.COLOR_GREY)
  50. draw_circle(Vector2(half, 0), cap, Params.COLOR_GREY)