Player.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using Godot;
  2. public class Player : Area2D
  3. {
  4. [Signal]
  5. public delegate void Hit();
  6. [Export]
  7. public int speed = 400; // How fast the player will move (pixels/sec).
  8. public Vector2 screenSize; // Size of the game window.
  9. public override void _Ready()
  10. {
  11. screenSize = GetViewportRect().Size;
  12. Hide();
  13. }
  14. public override void _Process(float delta)
  15. {
  16. var velocity = Vector2.Zero; // The player's movement vector.
  17. if (Input.IsActionPressed("move_right"))
  18. {
  19. velocity.x += 1;
  20. }
  21. if (Input.IsActionPressed("move_left"))
  22. {
  23. velocity.x -= 1;
  24. }
  25. if (Input.IsActionPressed("move_down"))
  26. {
  27. velocity.y += 1;
  28. }
  29. if (Input.IsActionPressed("move_up"))
  30. {
  31. velocity.y -= 1;
  32. }
  33. var animatedSprite = GetNode<AnimatedSprite>("AnimatedSprite");
  34. if (velocity.Length() > 0)
  35. {
  36. velocity = velocity.Normalized() * speed;
  37. animatedSprite.Play();
  38. }
  39. else
  40. {
  41. animatedSprite.Stop();
  42. }
  43. Position += velocity * delta;
  44. Position = new Vector2(
  45. x: Mathf.Clamp(Position.x, 0, screenSize.x),
  46. y: Mathf.Clamp(Position.y, 0, screenSize.y)
  47. );
  48. if (velocity.x != 0)
  49. {
  50. animatedSprite.Animation = "right";
  51. // See the note below about boolean assignment.
  52. animatedSprite.FlipH = velocity.x < 0;
  53. animatedSprite.FlipV = false;
  54. }
  55. else if (velocity.y != 0)
  56. {
  57. animatedSprite.Animation = "up";
  58. animatedSprite.FlipV = velocity.y > 0;
  59. }
  60. }
  61. public void Start(Vector2 pos)
  62. {
  63. Position = pos;
  64. Show();
  65. GetNode<CollisionShape2D>("CollisionShape2D").Disabled = false;
  66. }
  67. public void OnPlayerBodyEntered(PhysicsBody2D body)
  68. {
  69. Hide(); // Player disappears after being hit.
  70. EmitSignal(nameof(Hit));
  71. // Must be deferred as we can't change physics properties on a physics callback.
  72. GetNode<CollisionShape2D>("CollisionShape2D").SetDeferred("disabled", true);
  73. }
  74. }