Handling Keyboard and Mouse - sinusinu/Flora GitHub Wiki
Flora provides an interface called IInputHandler
for handling keyboard and mouse input.
An active IInputHandler
will receive input events via its On*
functions.
The simplest way to implement it is making your FloraCore
or IScreen
also inherit IInputHandler
.
Let's take a look!
Begin with Simple Program:
using Flora;
using Flora.Gfx;
using Flora.Input;
using System;
namespace FloraTest {
class MyCore : FloraCore, IInputHandler { // Note the addition of IInputHandler
public override void Prepare() {
Input.SetInputHandler(this);
}
public override void Pause() {
}
public override void Resume() {
}
public override void Resize(int width, int height) {
}
public override void Render(float delta) {
Gfx.Begin();
Gfx.End();
}
public override void Cleanup() {
}
public void OnKeyDown(KeyCode keycode) {
Console.WriteLine("Key {0} Pressed", Enum.GetName(keycode));
}
public void OnKeyUp(KeyCode keycode) {
Console.WriteLine("Key {0} Released", Enum.GetName(keycode));
}
public void OnMouseDown(MouseButton button, int x, int y) {
Console.WriteLine("Mouse {0} Button Pressed on ({1}, {2})", Enum.GetName(button), x, y);
}
public void OnMouseUp(MouseButton button, int x, int y) {
Console.WriteLine("Mouse {0} Button Released on ({1}, {2})", Enum.GetName(button), x, y);
}
public void OnMouseMove(int x, int y) {
Console.WriteLine("Mouse moved to ({0}, {1})", x, y);
}
public void OnMouseWheel(int x, int y) {
Console.WriteLine("Mouse Wheel rolled ({0}, {1})", x, y);
}
}
}
Our MyCore
is now inheriting IInputHandler
.
Now this MyCore
instance can be set as the active IInputHandler
by calling Input.SetInputHandler(this)
.
Flora will call these IInputHandler
functions as the event occur:
-
OnKeyDown(KeyCode)
- Called when the key is pressed down.
-
OnKeyUp(KeyCode)
- Called when the key is released.
-
OnMouseDown(MouseButton, int x, int y)
- Called when the mouse button is pressed down.
-
OnMouseUp(MouseButton, int x, int y)
- Called when the mouse button is released.
-
OnMouseMove(int x, int y)
- Called when the mouse moved.
-
OnMouseWheel(int x, int y)
- Called when the mouse wheel is scrolled.
When launched, various input logs from keyboard and mouse will be printed out to the console.
On FloraApplication
's main loop, Input events are fired right before the Render
function call.
If you are using View
, Mouse coordinates will be adjusted automatically to align with currently active View
. That is, if you have a View
set with position of (100, 0)
and you click the center point of the window, OnMouse*
functions will report (100, 0)
as the clicked position.