I'm trying to make a grid-based movement system, and I have a bug where the player will move an odd amount when multiple inputs come in. Is there a way to detect how many keys on the keyboard are being pushed?
For example, something like:
If(numberOfKeysDown > 1)
or something?
I know you can do touch counts if working with mobile, but I'm not sure about keys. Thanks for your time!
If you just want to actually test what you said it should be enough to check for Input.anyKey
Is any key or mouse button currently held down
if(Input.anyKey)
If you want to check specific keys you could use Input.GetKey and Linq Count like e.g.
// Fancy queries ;)
using System.Linq;
...
// The keycodes you wan to check
private HashSet<KeyCode> keysToCheck = { KeyCode.W, KeyCode.A, KeyCode.S, KeyCode.D };
int numberOfKeysPressed;
private void Update ()
{
numberOfKeysPressed = keysToCheck.Count(key => Input.GetKey(key));
// This basically equals doing
// var numberOfKeysPressed = 0;
// foreach(var key in KeyToCheck)
//{
// if(Input.GetKey(key)) numberOfKeysPressed++;
//}
}
Or you could use Input.GetKeyDown and Input.GetKeyUp and do something like
private HashSet<KeyCode> keysToCheck = { KeyCode.W, KeyCode.A, KeyCode.S, KeyCode.D };
int numberOfKeysPressed;
private void Update ()
{
foreach (var key in KeyToCheck)
{
if(Input.GetKeyDown(key)) numberOfKeysPressed++;
if(Input.GetKeyUp(key)) numberOfKeysPressed--;
}
}
If you want all KeyCode values you could use
private void Awake ()
{
keysToCheck = new HashSet<KeyCode>((KeyCode[])Enum.GetValues(typeof(KeyCode)));
}
If you really want to get the amount of any key presses on the keyboard it would probably be more efficient to directly use Event.current and do something like
HashSet<string> currentlyPressedKeys = new HashSet<string>();
void OnGUI ()
{
Event e = Event.current;
switch(e.type)
{
case EventType.KeyDown:
var key = e.keyCode.ToString();
if(!currentlyPressedKeys.Contains(key)) currentlypressedKeys.Add(key);
break;
case EventType.KeyUp:
var key = e.keyCode.ToString();
if(currentlyPressedKeys.Contains(key)) currentlypressedKeys.Remove(key);
break;
}
}
Now wherever you need to know you can do e.g
if(currentlyPressedKeys.Count > XY)
I dont think theres is a specific method for this.
You could however write your own counter method using Input.GetKeyDown.
Like so
int GetKeysDownCount() {
var keysDown = 0;
if(Input.GetKeyDown(KeyCode.W)
keysDown++;
if(Input.GetKeyDown(KeyCode.A)
keysDown++;
if(Input.GetKeyDown(KeyCode.S)
keysDown++;
if(Input.GetKeyDown(KeyCode.D)
keysDown++;
return keysDown;
}
https://docs.unity3d.com/ScriptReference/Input.GetKeyDown.html