- Home /
Pressing Keys in a Specific Order
Hi! I am making a game involving magic and I have a great idea how to cast spells. But I don't know what to write. This is what I want the console to say (not exactly).
//User pressed and is holding E, Starting Spell recognision
//Pressed LeftClick
//Pressed LeftClick
//Pressed RightClick
//Pressed LeftClick
//User let go of E, Recognising spell
//Spell is "Fire", Casting spell
BTW: Code can be in any language as long as you explain what each part does and what I need to change to add more spells.
Please accept my answer if it helped, otherwise give me more information. This hurts my answer acceptance rate.
Answer by Spinnernicholas · Oct 09, 2014 at 04:35 PM
Use Input.GetKeyDown and Input.GetKeyUp to determine when the user starts and stops holding the 'E' key down.
Then use Input.GetMouseButtonDown while E is being pressed to read mouse clicks. Note that:
button values are 0 for left button, 1 for right button, 2 for the middle button.
While tracking the clicks, add 'L' and 'R' to a "Spell String".
Then you just have to check it against your library of spell strings.
var fireBallSpell = "LLRLLRRL";
if(inputSpell == fireBallSpell)
{
castFireBall();
}
Thank you, since you don't have to check anything until after a key is released, you can simplify it quite a bit. And you can actually create a dictionary to register spell strings to objects.
"LRLRLRLLLLR" => "FireBallScriptComponent"
$$anonymous$$ake all spell scripts derive from a single parent class with an abstract method Cast();
Then you can do:
if(this.spellBook.Contains$$anonymous$$ey(spellString))
{
((SpellScript)gameObject.GetComponent(this.spellBook[spellString])).Cast();
}
Very cool. The Lambda expression is a little too deep for most beginners but great method.
Answer by Anxo · Oct 09, 2014 at 04:41 PM
This can just be solved with bools or stages. User holding down E can be handled like so
private bool eIsHeldDown = false;
public int FireSpellStage = 0;
void Update(){
eIsHeldDown = Input.GetKey(KeyCode.E);
if(eIsHeldDown){
if(FireSpellStage == 0 ){
if(Input.GetKeyDown(KeyCode.F)){
FireSpellStage = 1;
}
else if (FireSpellStage == 0){
if(Input.GetKeyDown(KeyCode.I)){
FireSpellStage = 0;
}
}
// And So on, till you made a combo you like.
}
}
else{
if(FireSpellStage == 4){
Debug.Log("Casting Fire Spell");
}
FireSpellStage = 0;
}
}
WUC (warrning, uncompiled code, check for errors. )