- Home /
How to detect if the shift key is tapped(pressed and released immediatly)
I want to make my character perform a roll every time i press the shift button(like for example in dark souls). I have the animation and everything, but i dont know how to make the code so it can tell the difference between pressing and releasing the shift key and holding it down.Any help?
Answer by WarmedxMints · Mar 24, 2019 at 09:14 PM
You can do it easily by having a small delay before it starts sprinting. If the key is released before that delay, roll instead.
private float _pressTime;
private const float _pressTimeTollerance = 0.5f;
private void Update()
{
if(Input.GetKey(KeyCode.LeftShift))
{
if(_pressTime < _pressTimeTollerance)
{
_pressTime += Time.deltaTime;
}
else
{
//Call sprint Method
}
}
else if(Input.GetKeyUp(KeyCode.LeftShift))
{
if(_pressTime < _pressTimeTollerance)
{
//Call Method to roll
}
_pressTime = 0f;
}
}
Answer by Esteem · Mar 24, 2019 at 08:01 PM
Listen for Input.GetKeyDown in Update() method
https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html
It will get called only once you press the shift key, then, all the other frames of you holding the shift key down will call Input.GetKey and when you release it it will call GetKeyUp (once again)
private void Update() {
if (Input.GetKeyDown(KeyCode.Shift)) {
// Do your thing
}
}
That's what i thought at the beginning, but i also want to make the player to be able to sprint, so if i do that, the player will be stuck in an infinite dodging loop. Any other ideas?
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# List and GUI 3 Answers
Stats effecting the max Health Value 2 Answers
how to add a function to Leveling a Character useing the Fibonacci sequence? 2 Answers