InputListener
This page is up to date for MonoGame.Extended 4.0.4
. If you find outdated information, please open an issue.
MonoGame.Extended offers input listeners that can be used to subscribe to input events instead of having to poll for input changes. These listeners include
KeyboardListener
MouseListener
GamePadListener
TouchListener
Using the Listeners
To get started using a listener, first create an instance of them
private readonly KeyboardListener _keyboardListener;
private readonly MouseListener _mouseListener;
private readonly GamePadListener _gamePadListener;
private readonly TouchListener _touchListener;
protected override void Initialize()
{
_keyboardListener = new KeyboardListener();
_gamePadListener = new GamePadListener();
_mouseListener = new MouseListener();
_touchListener = new TouchListener();
}
Next ensure that you update the listener each frame
protected override void Update(GameTime gameTime)
{
_keyboardListener.Update(gameTime);
_gamePadListener.Update(gameTime);
_mouseListener.Update(gameTime);
_touchListener.Update(gameTime);
}
Finally subscribe to any events of the listeners that you want to be notified about
private readonly KeyboardListener _keyboardListener;
private readonly MouseListener _mouseListener;
private readonly GamePadListener _gamePadListener;
private readonly TouchListener _touchListener;
protected override void Initialize()
{
_keyboardListener = new KeyboardListener();
_gamePadListener = new GamePadListener();
_mouseListener = new MouseListener();
_touchListener = new TouchListener();
_keyboardListener.KeyPressed += (sender, args) => { Window.Title = $"Key {args.Key} Pressed"; };
_mouseListener.MouseClicked += (sender, args) => { Window.Title = $"Mouse {args.Button} Clicked"; };
_gamePadListener.ButtonDown += (sender, args) => { Window.Title = $"Key {args.Button} Down"; };
_touchListener.TouchStarted += (sender, args) => { Window.Title = $"Touched"; };
}
Using the InputListenerComponent
MonoGame.Extended also provides an InputListenerComponent
that can be created and added to the game component collection to have it automatically updated for you each frame. Using it is similar to using hte individual listeners, you just have to create an instance of it and add it to the components collection
private readonly KeyboardListener _keyboardListener;
private readonly MouseListener _mouseListener;
private readonly GamePadListener _gamePadListener;
private readonly TouchListener _touchListener;
protected override void Initialize()
{
_keyboardListener = new KeyboardListener();
_gamePadListener = new GamePadListener();
_mouseListener = new MouseListener();
_touchListener = new TouchListener();
Components.Add(new InputListenerComponent(this, _keyboardListener, _gamePadListener, _mouseListener, _touchListener));
}