W
W
wide_e2021-07-20 13:22:52
C++ / C#
wide_e, 2021-07-20 13:22:52

When the button is pressed, the action is performed once. How can I make it run multiple times when pressed?

In my game, I want the player to move when the key is pressed until the button is released. And when I click, the action is performed only once. How to make the player move while the button is pressed? (I hope I explained it well)
Movement code:

using UnityEngine;

public class playermove : MonoBehaviour
{
    public Rigidbody rb;
 
    public float forwardForce = 2000f;
    public float sidewaysForce = 500f;

   
    void FixedUpdate()
    {
        rb.AddForce(0, 0, forwardForce * Time.deltaTime);
//Это отвечает за конец игры,  если что))
        if (rb.position.y < -1f)
        {
            FindObjectOfType<GameManager>().EndGame();
        }
    }
    
    public void RightButton()
    {
            rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }

    public void LeftButton()
    {
            rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
pashara, 2021-07-20
@pashara

Call RightButton() or LeftButton() while the button is pressed.
In general: to catch the event of pressing and releasing. While there is a trigger of the pressed key, call the methods you need in Update.

D
d1msk1y, 2021-07-20
@d1msk1y

If(Input.GetKey(KeyCode.Mouse0))
{
LeftButton();
}
If(Input.GetKey(KeyCode.Mouse1))
{
RightButton();
}
GetKey - When the button is pressed (Hold)
GetKeyDown - The action is performed once when the button is pressed
GetGeyUp - the action is performed once when the button is released

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question