Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Trying to cancel a KeyDown Button without releasing it

Discussion in 'Scripting' started by wittledemon, Jul 31, 2020.

  1. wittledemon

    wittledemon

    Joined:
    Mar 27, 2017
    Posts:
    16
    I am attempting to cancel the first if at signs of death or at thruster <= 0 but every combination of the if statement seems to keep breaking the speed variable and the thruster sprite doesn't shut off on death or when thruster bar hits 0.

    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.LeftShift))
    2.         {
    3.             gameObject.GetComponent<SpriteRenderer>().enabled = true;
    4.             player.IncreaseCurrentSpeed(_increaseSpeed);
    5.             _thrustersState = true;
    6.         }
    7.         else if (Input.GetKeyUp(KeyCode.LeftShift))
    8.         {
    9.             gameObject.GetComponent<SpriteRenderer>().enabled = false;
    10.             player.DecreaseCurrentSpeed(_increaseSpeed);
    11.             _thrustersState = false;
    12.         }

    Attempts
    playerState() = bool isDead

    * gave first if && player.State() != true && thrusterGuage.GetIndex() > 0
    * was going to add || additions to second if statement but realized that would decrease the speed variable ever frame so canceled that line of thought.
     
  2. WarmedxMints

    WarmedxMints

    Joined:
    Feb 6, 2017
    Posts:
    1,011
    Sounds like you need to be evaluating the else if and not the first. From what I can gather, you want to cancel the thrust if the player dies or the thruster charge is depleted. GetKeyDown and Up only evaluate true for the frame in which the defined button is pressed or released, so don't add to them rather also run the code if other factors are true.

    This should do it, although I would imagine it could be cleaned up a bit. Hard to say without seeing more code.

    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.LeftShift))
    2. {
    3.     gameObject.GetComponent<SpriteRenderer>().enabled = true;
    4.     player.IncreaseCurrentSpeed(_increaseSpeed);
    5.     _thrustersState = true;
    6. }
    7. else if (Input.GetKeyUp(KeyCode.LeftShift) || _thrustersState && (thrusterGuage.GetIndex() <= 0 || player.State() != true))
    8. {
    9.     gameObject.GetComponent<SpriteRenderer>().enabled = false;
    10.     player.DecreaseCurrentSpeed(_increaseSpeed);
    11.     _thrustersState = false;
    12. }
     
  3. wittledemon

    wittledemon

    Joined:
    Mar 27, 2017
    Posts:
    16
    Thank you very much it wasn't quite correct but it got me in the correct direction I needed to go in to get it working. Very helpful.
     
unityunity