Switching Scenes

You'll eventually come to a point where you'll need to have multiple Scenes in your game, and when you have multiple Scenes you'll want to switch between them.  Otter has a very simple way of doing this with just the Game class.  You can use the SwitchScene method to change the current active scene.  Keep in mind that when you switch scenes the change is not instant. The actual scene switch will happen at the end of the current update.

using Otter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SwitchScenes {
  class Program {
    static void Main(string[] args) {
      // Create a game.
      var game = new Game("Switch Scenes");
      // Start the game using FirstScene.
      game.Start(new FirstScene());
    }
  }

  class FirstScene : Scene {

    public FirstScene() : base() {
      // Add a blue rectangle to the Scene (just to indicate which scene is currently active.)
      AddGraphic(Image.CreateRectangle(Game.Instance.Width, Game.Instance.Height, Color.Blue));
    }

    public override void Update() {
      base.Update();

      if (Input.KeyPressed(Key.Space)) {
        // When the space bar is pressed switch to the SecondScene.
        Game.SwitchScene(new SecondScene());
      }
    }

  }

  class SecondScene : Scene {

    public SecondScene() : base() {
      // Add a red rectangle to the Scene (just to indicate which scene is currently active.)
      AddGraphic(Image.CreateRectangle(Game.Instance.Width, Game.Instance.Height, Color.Red));
    }

    public override void Update() {
      base.Update();

      if (Input.KeyPressed(Key.Space)) {
        // When the space bar is pressed switch to the FirstScene.
        Game.SwitchScene(new FirstScene());
      }
    }
  }
}

The above example will simply switch between a Scene that has a red rectangle, and a Scene that has a blue rectangle. Press the space bar to switch between the two Scenes.

Scenes have a few methods that are called when switching.  Check out Begin and End to execute code when your Scene begins and ends.

Examples