- Home /
Separating Input.GetKey and Input.GetKeyDown
I'm using the observer pattern to create a layer of abstraction between player input and game logic. I have an InputManager class that other classes can subscribe to to listen for keypresses they're interested in. I've come across an issue where I need to differentiate between Input.GetKey and Input.GetKeyDown calls. E.g. Some spells can be cast as soon as they come off cooldown by holding down the key, but others can't. This would be a trivial fix if I hardcoded the condition into the spell script, but I'd rather keep all inputs in the InputManager class. How can I achieve this?
I'm not sure I understand the problem: in the frame in which a key is pressed, both Get$$anonymous$$ey and Get$$anonymous$$eyDown are true because that's how they're defined ("Returns true if they key is down" and "returns true in the first frame in which the key is down").
If you want to "separate" them (by which I assume you want to make them mutually exclusive) you're going to have to change their definitions.
Answer by BenKurdziel · Oct 04, 2014 at 05:48 AM
I'd make a bool like "RefreshKeyPress" that you toggle. And a bool for each spell that checks if it requires you to "Refresh" your key press before it activates again.
Without testing anything, this is my guess at it:
so like
if (Input.GetKey(KeyCode.Q))
{
if (spell1.requireRefresh)
{
if (RefreshKeyPress)
spell1.CastSpell();
}
else
spell1.CastSpell();
RefreshKeyPress = false;
}
else if (Input.GetKey(KeyCode.W))
{
if (spell2.requireRefresh)
{
if (RefreshKeyPress)
spell2.CastSpell();
}
else
spell2.CastSpell();
RefreshKeyPress = false;
}
else
{
RefreshKeyPress = true;
}
Oh, and obviously you'd need to check the recharge time of the spell inside your CastSpell function in this instance. Otherwise you could always access it with spell1.CheckRecharge() or something and return true or false
if (spell1.CheckRecharge())
{
}
//In your spell's script
public bool CheckRecharge ()
{
if (time >= rechargeTime)
return true;
else
return false;
}