How can I get event based, or recognize async key presses in C# .Net 7?
This is for player controls in a console application, so obviously I cannot have the game loop wait around for a button press, but maybe I could buffer it? I am trying to get key presses to then let the camera know that it needs to turn, pan, move etc. without having the console halt the game loop.
I was using the following code translated from C++ as a base, and I was trying to find a similar solution in C#.
int LeftTurn = (ushort)'A';
int RightTurn = (ushort)'D';
if (GetAsyncKeyState(LeftTurn) & 0x8000)
fPlayerA -= (0.1f);
if (GetAsyncKeyState(RightTurn) & 0x8000)
fPlayerA += (0.1f);
It appears there is a way to get GetAsyncKeyState to work with C# by importing a DLL, but I could not get it to work as it kept throwing errors at the DLL placement and at the function. So I tried using the following instead
if (Keyboard.IsKeyDown(LeftTurn))
fPlayerA -= (0.1f);
if (Keyboard.IsKeyDown(RightTurn))
fPlayerA += (0.1f);
However this seems to only be supported in Windows desktop 7 and is not supported by .Net 7. Errors were thrown every time I tried to evoke Keyboard. Is there something simple I am missing in either of these two methods or is there a better way to go about this?
This has me stumped, thanks.
edit: I've tried copying some code I found on reddit that went like:
if(Input.IsKeyPressed((int) KeyList.W))
{
direction.y -= Speed * delta;
}
but I keep getting the error that "Error CS0234 The type or namespace name 'IsKeyPressed' does not exist in the namespace 'System.Windows.Input' (are you missing an assembly reference?)" I'm very confused since every potential solution gives me this error, despite making sure that I declare that I am referencing the required files.
My code looks a bit like this:
using System.ComponentModel;
using System.Numerics;
using System.Reflection.Metadata;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Windows.Input;
class GameApp
{
//Main Funtion
static void Main()
{
//frame settings
//camera variables
//Level data
Console.SetWindowPosition(0, 0);
Console.SetWindowSize(nFrameWidth, nFrameHeight);
Console.CursorVisible = false;
//game loop
while (true)
{
//User input
//Camera Controls
//Handle Rotation
int LeftTurn = (ushort)'A';
int RightTurn = (ushort)'D';
if (Keyboard.IsKeyDown(LeftTurn))
fPlayerA -= (0.1f) * fElapsedTime;
if (Keyboard.IsKeyDown(RightTurn))
fPlayerA += (0.1f) * fElapsedTime;
//Render Frame
//lots of math here
}
}
}
I cut out the sections that shouldn't be relevant to save space and left comments for what the sections are supposed to do. Please help, thanks.