ball.gd 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. extends Area2D
  2. const DEFAULT_SPEED = 100
  3. var direction = Vector2.LEFT
  4. var stopped = false
  5. var _speed = DEFAULT_SPEED
  6. @onready var _screen_size = get_viewport_rect().size
  7. func _process(delta):
  8. _speed += delta
  9. # Ball will move normally for both players,
  10. # even if it's sightly out of sync between them,
  11. # so each player sees the motion as smooth and not jerky.
  12. if not stopped:
  13. translate(_speed * delta * direction)
  14. # Check screen bounds to make ball bounce.
  15. var ball_pos = position
  16. if (ball_pos.y < 0 and direction.y < 0) or (ball_pos.y > _screen_size.y and direction.y > 0):
  17. direction.y = -direction.y
  18. if is_multiplayer_authority():
  19. # Only the master will decide when the ball is out in
  20. # the left side (it's own side). This makes the game
  21. # playable even if latency is high and ball is going
  22. # fast. Otherwise ball might be out in the other
  23. # player's screen but not this one.
  24. if ball_pos.x < 0:
  25. get_parent().update_score.rpc(false)
  26. _reset_ball.rpc(false)
  27. else:
  28. # Only the puppet will decide when the ball is out in
  29. # the right side, which is it's own side. This makes
  30. # the game playable even if latency is high and ball
  31. # is going fast. Otherwise ball might be out in the
  32. # other player's screen but not this one.
  33. if ball_pos.x > _screen_size.x:
  34. get_parent().update_score.rpc(true)
  35. _reset_ball.rpc(true)
  36. @rpc("any_peer", "call_local")
  37. func bounce(left, random):
  38. # Using sync because both players can make it bounce.
  39. if left:
  40. direction.x = abs(direction.x)
  41. else:
  42. direction.x = -abs(direction.x)
  43. _speed *= 1.1
  44. direction.y = random * 2.0 - 1
  45. direction = direction.normalized()
  46. @rpc("any_peer", "call_local")
  47. func stop():
  48. stopped = true
  49. @rpc("any_peer", "call_local")
  50. func _reset_ball(for_left):
  51. position = _screen_size / 2
  52. if for_left:
  53. direction = Vector2.LEFT
  54. else:
  55. direction = Vector2.RIGHT
  56. _speed = DEFAULT_SPEED