tags:

views:

22

answers:

1

I have an interface (ICamera) which is implemented by 2 classes (FreeCamera, StaticCamera). The classes are inheriting from GameComponent.

Example definiton:

public class FreeCamera : GameComponent, ICamera
{
  ...
}

Now I'm adding the classes to the Game Components and register one of the components to a game service

private FreeCamera freeCam;
private StaticCamera staticCam;

public Game1()
{
  graphics = new GraphicsDeviceManager(this);
  Content.RootDirectory = "Content";
  freeCam = new FreeCamera(this) { Enabled = true };
  staticCam = new StaticCamera(this) { Enabled = false };
  Services.AddService(typeof(ICamera, freeCam);
  Components.Add(freeCam);
  Components.Add(staticCam);
  ...
}

Then I want to change the provider for the service during the application flow with help of a toggle function

namespace Game1
{
  protected override void Update(GameTime gameTime)
  {
    var keyboard = Keyboard.GetState();
    if(keyboard.IsKeyDown(Keys.C))
    {
      if(freeCam.Enabled)
      {
        Services.RemoveService(typeof(ICamera));
        Services.AddService(typeof(ICamera, staticCam);
        freeCam.Enabled = !freeCam.Enabled;
        staticCam.Enabled = !staticCam.Enabled;
      }
      else
      {
        Services.RemoveService(typeof(ICamera));
        Services.AddService(typeof(ICamera, freeCam);
        freeCam.Enabled = !freeCam.Enabled;
        staticCam.Enabled = !staticCam.Enabled;
      }         
    }
    base.Update(gameTime);
  }
}

The StaticCamera takes only input by mouse (you can rotate the camera), the FreeCamera can also moved by keyboard input. When I call the method above (by pressing C on the keyboard) the FreeCamera class gets deactivated but the viewport seems frozen and does not react to any input. When I call the method again after a short time the FreeCamera gets activated again and everything works as expected.

Now I have 2 questions regarding this:

  • Is it possible to change the service provider of a game service in the game loop?
  • Is there a better approach to handle different camera types in a game and switch between them easily?

Thanks in advance for any help.

A: 

Thanks for the tip. I just wrote the code down from my head without my IDE at hand, so please do not look too much into syntax errors etc.

In my game I'm using wrapper classes for the input. The code is just a brief example of the problem - how to substitute a game service if both classes are using the same interface.

My new idea: I could use a "manager" class (like CameraManager in this case) which has the following methods

public void SetCameraType(CameraType type) //CameraType could be an enum
public ICamera GetCamera()

and then put the manager class into the service (with its own interface like ICameraManager).

Edit: this was considered as an answer to the comment above ... but it seems I clicked the wrong button - sorry

organic