Paddle.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using Godot;
  2. using System;
  3. public partial class Paddle : Area2D
  4. {
  5. private const int MoveSpeed = 100;
  6. // All three of these change for each paddle.
  7. private int _ballDir;
  8. private string _up;
  9. private string _down;
  10. public override void _Ready()
  11. {
  12. string name = Name.ToLower();
  13. _up = name + "_move_up";
  14. _down = name + "_move_down";
  15. _ballDir = name == "left" ? 1 : -1;
  16. }
  17. public override void _Process(float delta)
  18. {
  19. // Move up and down based on input.
  20. float input = Input.GetActionStrength(_down) - Input.GetActionStrength(_up);
  21. Vector2 position = Position; // Required so that we can modify position.y.
  22. position += new Vector2(0, input * MoveSpeed * delta);
  23. position.y = Mathf.Clamp(position.y, 16, GetViewportRect().Size.y - 16);
  24. Position = position;
  25. }
  26. public void OnAreaEntered(Area2D area)
  27. {
  28. if (area is Ball ball)
  29. {
  30. // Assign new direction
  31. ball.direction = new Vector2(_ballDir, ((float)new Random().NextDouble()) * 2 - 1).Normalized();
  32. }
  33. }
  34. }