ball.gd 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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_network_master():
  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().rpc("update_score", false)
  26. rpc("_reset_ball", 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().rpc("update_score", true)
  35. rpc("_reset_ball", true)
  36. remotesync func bounce(left, random):
  37. # Using sync because both players can make it bounce.
  38. if left:
  39. direction.x = abs(direction.x)
  40. else:
  41. direction.x = -abs(direction.x)
  42. _speed *= 1.1
  43. direction.y = random * 2.0 - 1
  44. direction = direction.normalized()
  45. remotesync func stop():
  46. stopped = true
  47. remotesync func _reset_ball(for_left):
  48. position = _screen_size / 2
  49. if for_left:
  50. direction = Vector2.LEFT
  51. else:
  52. direction = Vector2.RIGHT
  53. _speed = DEFAULT_SPEED