How To: Input
Standard MonoGame input APIs work as-is inside Avalonia — no special wiring required.
Call them from Update(GameTime gameTime) exactly as you would in a standalone MonoGame project.
Reference files:
Minimal/MinimalGame.cs (keyboard/mouse) ·
Advanced/SampleGame.cs (gamepad)
Keyboard
protected override void Update(GameTime gameTime)
{
var kb = Keyboard.GetState();
var dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (kb.IsKeyDown(Keys.Left)) _x -= 150f * dt;
if (kb.IsKeyDown(Keys.Right)) _x += 150f * dt;
if (kb.IsKeyDown(Keys.Up)) _y -= 150f * dt;
if (kb.IsKeyDown(Keys.Down)) _y += 150f * dt;
base.Update(gameTime);
}
Keyboard.GetState() reflects the key state that Avalonia reports via its KeyDown /
KeyUp events. Focus must be on the MonoGameControl (or its parent window) for key
events to reach it.
Edge detection (pressed this frame, not last)
private KeyboardState _prevKeyState;
protected override void Update(GameTime gameTime)
{
var kb = Keyboard.GetState();
if (kb.IsKeyDown(Keys.Space) && _prevKeyState.IsKeyUp(Keys.Space))
FireWeapon();
_prevKeyState = kb;
base.Update(gameTime);
}
Mouse
protected override void Update(GameTime gameTime)
{
var mouse = Mouse.GetState();
bool leftDown = mouse.LeftButton == ButtonState.Pressed;
bool rightDown = mouse.RightButton == ButtonState.Pressed;
int x = mouse.X;
int y = mouse.Y;
base.Update(gameTime);
}
Mouse coordinates are in the game's viewport space (pixels from the top-left of @Thunder.MonoGame.Avalonia.Controls.MonoGameControl).
Gamepad
protected override void Update(GameTime gameTime)
{
var pad = GamePad.GetState(PlayerIndex.One);
if (pad.IsConnected)
{
float lx = pad.ThumbSticks.Left.X;
float ly = pad.ThumbSticks.Left.Y;
if (pad.Buttons.A == ButtonState.Pressed)
Jump();
}
base.Update(gameTime);
}
Gamepad state is polled by SdlControllerPump — a background thread that reads SDL2
controller events. It is started automatically by the Avalonia platform backend
(AvaloniaGamePlatform) when the game initialises, so no manual setup is needed.
Note:
SdlControllerPumprequires SDL2 to be present on the host system. On most desktop Linux distributions SDL2 is available via the system package manager. On Windows and macOS it ships with MonoGame's native libraries.