-1

Im trying to write a code using SFML library, when I press a key I change a bool variable. The problem is that I use key presses and I don't know how to implement key release who only works 1 time x key and that's what I'm trying to implement cause key press affects multiple times changing all time the variable.

if (Keyboard.IsKeyPressed(Keyboard.Key.A))
{
    values[0] = !values[0];
}
if (Keyboard.IsKeyPressed(Keyboard.Key.S))
{
    values[1] = !values[1];
}
if (Keyboard.IsKeyPressed(Keyboard.Key.D))
{
    values[2] = !values[2];
}

Thanks

Neuron
  • 5,141
  • 5
  • 38
  • 59
Nocte
  • 1

1 Answers1

1

I think you can use Window.KeyPressed and Window.KeyReleased and save which key was pressed and released

private Dictionary<Keyboard.Key, bool> keysArePressed = new Dictionary<Keyboard.Key, bool>
{
   {Keyboard.Key.A, false},
   {Keyboard.Key.S, false},
   {Keyboard.Key.D, false}
};

// Key
Window.KeyPressed += OnKeyPressed;
Window.KeyReleased += OnKeyReleased;

public void OnKeyPressed(object sender, KeyEventArgs e)
{
   if (e.Code == Keyboard.Key.A && !keysArePressed[Keyboard.Key.A])
   {
      Console.WriteLine("A pressed");
      keysArePressed[Keyboard.Key.A] = true;
   }
}

public void OnKeyReleased(object sender, KeyEventArgs e)
{
   if (e.Code == Keyboard.Key.A)
   {
      Console.WriteLine("A released");
      keysArePressed[Keyboard.Key.A] = false;
   }
}