Paddle.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using Godot;
  2. using System;
  3. public partial class Paddle : Area2D
  4. {
  5. private const int MotionSpeed = 150;
  6. [Export] private bool _left = false;
  7. private float _motion = 0.0f;
  8. private bool _youHidden = false;
  9. private float _screenSizeY = 0.0f;
  10. public override void _Ready()
  11. {
  12. _screenSizeY = GetViewportRect().Size.y;
  13. }
  14. public override void _Process(float delta)
  15. {
  16. // Is the master of the paddle.
  17. if (IsNetworkMaster())
  18. {
  19. _motion = Input.GetActionStrength("move_down") - Input.GetActionStrength("move_up");
  20. if (!_youHidden && _motion != 0)
  21. {
  22. HideYouLabel();
  23. }
  24. _motion *= MotionSpeed;
  25. // Using unreliable to make sure position is updated as fast as possible,
  26. // even if one of the calls is dropped
  27. RpcUnreliable(nameof(SetPosAndMotion), Position, _motion);
  28. }
  29. else
  30. {
  31. if (!_youHidden)
  32. {
  33. HideYouLabel();
  34. }
  35. }
  36. Translate(new Vector2(0, _motion * delta));
  37. // Set screen limits. Can't modify structs directly, so we create a new one.
  38. Position = new Vector2(Position.x, Mathf.Clamp(Position.y, 16, _screenSizeY - 16));
  39. }
  40. [Puppet]
  41. private void SetPosAndMotion(Vector2 pos, float motion)
  42. {
  43. Position = pos;
  44. _motion = motion;
  45. }
  46. private void HideYouLabel()
  47. {
  48. _youHidden = true;
  49. GetNode<Label>("You").Hide();
  50. }
  51. private void OnPaddleAreaEnter(Area2D area)
  52. {
  53. if (IsNetworkMaster())
  54. {
  55. area.Rpc("Bounce", _left, GD.Randf());
  56. }
  57. }
  58. }