Home > Blockchain >  How do I make something happen ONCE when a button pressed but not WHILE it is held?
How do I make something happen ONCE when a button pressed but not WHILE it is held?

Time:05-08

Sorry if this has been asked already, I searched but none of the answers seemed to apply to what I'm doing. I am using Unity with C# and have a character jump when the jump button is pressed (moveVertical).

private float moveVertical;
moveVertical = Input.GetAxisRaw("Vertical);

if (moveVertical > 0.1f)
{
    rb2D.AddForce(new Vector2(0f, moveVertical * jumpForce), ForceMode2D.Impulse);
}

The problem is that this triggers every frame while the button is held. I want the character to be able to jump in the air (i.e. Kirby) but only have it trigger once for each button press. I'm a newbie so I don't know the term for that in C#.

CodePudding user response:

Fortunately, Unity offers a variety of input systems that simplify the task. I think you are looking for this:

public void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        // trigger once when press space key
    }
    
    if (Input.GetKey(KeyCode.Space))
    {
        // trigger while pressing space key
    }
}

Specifically to create the jump you can use the Input.GetKeyDown code as below:

private Rigidbody2D rb2D;

public void Update()
{
    if (Input.GetKeyDown(KeyCode.Space)) Jump(300f); // 300 for example..
}

public void Jump(float force) => rb2D.AddForce(Vector2.up * force);

CodePudding user response:

You can use Input.GetButtonDown("Jump") (manual page) for that.

It returns 'true' in the exact frame the key is pressed. Keep in mind that you'll need to assing a "positive button" for that in the Input Manager if you didn't already. I'm not sure if you "Vertical" Axis will work with that.

  • Related