In this tutorial, we want to learn how to react to keyboard input. We start from the "hello triangle" program given in the Get Going section.
Let us make it a bit more fun by giving the user the possibility to control this triangle and manouver it around in the scene. You can declare a local event handler in the Main()-method and pass it to the window-constructor as an additional last argument.
void ActOnKey(IInputEvent e, ConsoleKey key, Action action)
{
if (e is KeyInputEvent ke && ke.Key == key && ke.Pressing == Pressing.Down) action();
}
void EventHandler(IInputEvent e)
{
ActOnKey(e, ConsoleKey.A, rendering.MoveLeft);
ActOnKey(e, ConsoleKey.S, rendering.MoveDown);
ActOnKey(e, ConsoleKey.D, rendering.MoveRight);
ActOnKey(e, ConsoleKey.W, rendering.MoveUp);
}
We obviously need to add the methods above to the new rendering class and move the triangle around accordingly. Introduce a private field referring to the triangle private VisualPart? _triangle;. Apply a translation to _figure that corresponds the method name, e.g. public void MoveLeft() => _triangle?.Translate(-0.1f * Vector3.UnitX);. When running the program, you should now be able to move the figure around in the window by pressing the keys above. It looks better, if the triangle is rotated additionally to the translation in the direction of the move. This is achieved by the following code added to the rendering that uses an absolute approach to define a transformation.
private int _x;
private int _y;
private float _angle;
public void MoveLeft()
{
_x--;
_angle = 0.5f * MathF.PI;
UpdateTranslation();
}
private void UpdateTranslation()
{
_triangle!.Transform =
Matrix4.RotationZ(_angle) *
Matrix4.Translation(0.1f * (_x * Vector3.UnitX + _y * Vector3.UnitY));
}