Paddle.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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.ToString().ToLower();
  13. _up = name + "_move_up";
  14. _down = name + "_move_down";
  15. _ballDir = name == "left" ? 1 : -1;
  16. }
  17. public override void _Process(double 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 * (float)delta);
  23. position = new(position.X, Mathf.Clamp(position.Y, 16, GetViewportRect().Size.X - 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. }