Player.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using Godot;
  2. public partial class Player : Area2D
  3. {
  4. [Signal]
  5. public delegate void HitEventHandler();
  6. [Export]
  7. public int Speed { get; set; } = 400; // How fast the player will move (pixels/sec).
  8. public Vector2 ScreenSize { get; set; } // Size of the game window.
  9. public override void _Ready()
  10. {
  11. ScreenSize = GetViewportRect().Size;
  12. Hide();
  13. }
  14. public override void _Process(double delta)
  15. {
  16. var velocity = Vector2.Zero;
  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<AnimatedSprite2D>("AnimatedSprite2D");
  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 * (float)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. animatedSprite.FlipV = false;
  52. animatedSprite.FlipH = velocity.X < 0;
  53. }
  54. else if (velocity.Y != 0)
  55. {
  56. animatedSprite.Animation = "up";
  57. animatedSprite.FlipV = velocity.Y > 0;
  58. }
  59. }
  60. public void Start(Vector2 position)
  61. {
  62. Position = position;
  63. Show();
  64. GetNode<CollisionShape2D>("CollisionShape2D").Disabled = false;
  65. }
  66. public void OnBodyEntered(PhysicsBody2D body)
  67. {
  68. Hide(); // Player disappears after being hit.
  69. EmitSignal(SignalName.Hit);
  70. // Must be deferred as we can't change physics properties on a physics callback.
  71. GetNode<CollisionShape2D>("CollisionShape2D").SetDeferred(CollisionShape2D.PropertyName.Disabled, true);
  72. }
  73. }