简体   繁体   中英

C# Input Key, one click, So it doesn't respond to being held down

So i am creating a movement script for my character, and i want him to move 1 square every a button is pressed, the problem i am having is that, if i hold down the button, he will constantly move which i don't want, for example if it was held down i still only want him to move 1 square. I have already tried using

if (Input.GetKeyDown(KeyCode.W) && WButton == true)
{
    transform.Translate(0, 0, 1);
    WButton = false;
}
if (Input.GetKeyUp(KeyCode.W))
{
    WButton = true;
}

what this does is, when the W button is pressed down it disables it, and when you lift your finger up it then enables it. This does what i want but it doesn't work very well at all, like definitely not good enough to be in a game, so is there any other ways that i am able to achieve this. Thanks for all the help, it is well appreciated

By your given example, I assume you are using Unity3D, right? (if so, please consider adding the unity3d tag to your question, in order for people to have a better context of your problem and find your question in the appropriate sections of StackOverflow).

Your code example seems right. The problem that might be happening is that you can only read input values from the Update() method, as stated in the Input class documentation .

If you are calling Input.GetKeyDown() and/or Input.GetKeyUp() from any place other than inside an Update() method, then these methods will return inconsistent/erroneous values.

Input.GetKeyDown called only first time that you press the button; So you don't need to use bool WButton .

Refer to Unity3D documentation - Input.GetKeyDown , "You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the key and pressed it again."

Use this code:

void Update()
{
    if (Input.GetKeyDown(KeyCode.W))
        transform.Translate(0, 0, 1);
}

I hope it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM