-2

I've got into game development, and I decided to choose Godot as the game engine because C# was supported, and I knew the language. I've been working on a simple game, and at some point, I ran into a problem. I wanted to make a sprite invisible when a key was pressed. I wanted It so if the key was pressed, it did an action permanently.

I tried this, but Input.IsPhysicalKeyPressed((int)) stopped the action as soon as I released the key

  public override void _PhysicsProcess(float delta)
  {
    Visible = true;
    if (Input.IsPhysicalKeyPressed((int)KeyList.W) || Input.IsPhysicalKeyPressed((int)KeyList.A) || Input.IsPhysicalKeyPressed((int)KeyList.S) || Input.IsPhysicalKeyPressed((int)KeyList.D))
    {
      Visible = false;
    }
    else if (Input.IsPhysicalKeyPressed((int)KeyList.Up) || Input.IsPhysicalKeyPressed((int)KeyList.Left) || Input.IsPhysicalKeyPressed((int)KeyList.Down) || Input.IsPhysicalKeyPressed((int)KeyList.Right))
    {
      Visible = false;
    }
  }

How do I fix this problem?

4
  • Is the unconditional Visible = true; the problem? If your game runs at 60fps, I imagine that _PhysicsProcess is being executed 60 times a second. Wouldn't that immediately make the item visible again when you release whichever key of WSAD⬆️⬇️⬅️➡️ you have pressed? Commented Nov 12, 2022 at 13:59
  • Yep, that's what I said, when I release the key the sprite re-appears,and i want a solution.
    – George
    Commented Nov 12, 2022 at 14:56
  • So remove the line that says Visible = true; and that will solve it, won't it? Commented Nov 12, 2022 at 15:10
  • 1
    Why are the simple things always hard for me to guess? thank you btw, my idiotic brain really needed it
    – George
    Commented Nov 12, 2022 at 16:41

1 Answer 1

0

From what I can see, you always set Visible back to true. If you want to have a toggle, you will need to set Visible to the opposite of Visible:

public override void _PhysicsProcess(float delta)
{
    if (Input.IsPhysicalKeyPressed((int)KeyList.W) || Input.IsPhysicalKeyPressed((int)KeyList.A) || Input.IsPhysicalKeyPressed((int)KeyList.S) || Input.IsPhysicalKeyPressed((int)KeyList.D))
    {
      Visible = !Visible;
    }
    else if (Input.IsPhysicalKeyPressed((int)KeyList.Up) || Input.IsPhysicalKeyPressed((int)KeyList.Left) || Input.IsPhysicalKeyPressed((int)KeyList.Down) || Input.IsPhysicalKeyPressed((int)KeyList.Right))
    {
      Visible = !Visible;
    }
}

This will not work tho, because it would just toggle the visiblity as long as the key is pressed. To fix that, you will need to add a way to check if the key has been lifted again, and only then make it able to change the visibility.

I have never worked with the Godot Game Engine, so I am not sure how that works. I am sure that if you don't know it, a simple google search will do it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.