Main.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using Godot;
  2. public partial class Main : Node
  3. {
  4. #pragma warning disable 649
  5. // We assign this in the editor, so we don't need the warning about not being assigned.
  6. [Export]
  7. public PackedScene mobScene;
  8. #pragma warning restore 649
  9. public int score;
  10. public override void _Ready()
  11. {
  12. GD.Randomize();
  13. }
  14. public void GameOver()
  15. {
  16. GetNode<Timer>("MobTimer").Stop();
  17. GetNode<Timer>("ScoreTimer").Stop();
  18. GetNode<HUD>("HUD").ShowGameOver();
  19. GetNode<AudioStreamPlayer>("Music").Stop();
  20. GetNode<AudioStreamPlayer>("DeathSound").Play();
  21. }
  22. public void NewGame()
  23. {
  24. // Note that for calling Godot-provided methods with strings,
  25. // we have to use the original Godot snake_case name.
  26. GetTree().CallGroup("mobs", "queue_free");
  27. score = 0;
  28. var player = GetNode<Player>("Player");
  29. var startPosition = GetNode<Position2D>("StartPosition");
  30. player.Start(startPosition.Position);
  31. GetNode<Timer>("StartTimer").Start();
  32. var hud = GetNode<HUD>("HUD");
  33. hud.UpdateScore(score);
  34. hud.ShowMessage("Get Ready!");
  35. GetNode<AudioStreamPlayer>("Music").Play();
  36. }
  37. public void OnStartTimerTimeout()
  38. {
  39. GetNode<Timer>("MobTimer").Start();
  40. GetNode<Timer>("ScoreTimer").Start();
  41. }
  42. public void OnScoreTimerTimeout()
  43. {
  44. score++;
  45. GetNode<HUD>("HUD").UpdateScore(score);
  46. }
  47. public void OnMobTimerTimeout()
  48. {
  49. // Note: Normally it is best to use explicit types rather than the `var`
  50. // keyword. However, var is acceptable to use here because the types are
  51. // obviously PathFollow2D and Mob, since they appear later on the line.
  52. // Choose a random location on Path2D.
  53. var mobSpawnLocation = GetNode<PathFollow2D>("MobPath/MobSpawnLocation");
  54. mobSpawnLocation.Offset = GD.Randi();
  55. // Create a Mob instance and add it to the scene.
  56. var mob = (Mob)mobScene.Instantiate();
  57. AddChild(mob);
  58. // Set the mob's direction perpendicular to the path direction.
  59. float direction = mobSpawnLocation.Rotation + Mathf.Pi / 2;
  60. // Set the mob's position to a random location.
  61. mob.Position = mobSpawnLocation.Position;
  62. // Add some randomness to the direction.
  63. direction += (float)GD.RandRange(-Mathf.Pi / 4, Mathf.Pi / 4);
  64. mob.Rotation = direction;
  65. // Choose the velocity for the mob.
  66. var velocity = new Vector2((float)GD.RandRange(150.0, 250.0), 0);
  67. mob.LinearVelocity = velocity.Rotated(direction);
  68. }
  69. }