- Home /
How to do something if two keys are pressed at the same time in a specific order?
Hi, so I am making an fps game, and i made animations for walking in 4 directions: walking forward, walking backwards, walking left and walking right, i am using the animator but my "problem" is that when i am pressing "a" (is playing the "walking left" animation), and then i press "d" (while pressing a), it plays the animation to go to the right, but i want it to keep playing the "walking left" animation until i release the "a" key so the character can finally play the "walking right" animation. My code is this one.
public class FPSController : MonoBehaviour {
static Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
anim.SetInteger ("isWalking", 0);
}
// Update is called once per frame
void Update () {
bool isForward;
bool isBack;
bool isLeft;
bool isRight;
isForward = Input.GetKeyDown ("w");
isBack = Input.GetKeyDown ("s");
isLeft = Input.GetKeyDown ("a");
isRight = Input.GetKeyDown ("d");
if (isForward == true) {
anim.SetFloat("Speed", 0.0f);
anim.SetInteger ("isWalking", 1);
}
if (isBack == true) {
anim.SetFloat("Speed", 0.5f);
anim.SetInteger ("isWalking", 1);
}
if (isLeft == true) {
anim.SetFloat("Speed", 1.0f);
anim.SetInteger ("isWalking", 1);
}
if (isRight == true) {
anim.SetFloat("Speed", 1.5f);
anim.SetInteger ("isWalking", 1);
}
if(Input.anyKey == false){
anim.SetInteger ("isWalking", 0);
}
if (Input.GetButtonDown ("Fire2")) {
anim.SetBool ("isAiming", true);
}
if (Input.GetButtonUp ("Fire2")) {
anim.SetBool ("isAiming", false);
}
if (Input.GetKeyDown (KeyCode.LeftShift)) {
anim.SetInteger ("isWalking", 2);
}
if (Input.GetKeyUp (KeyCode.LeftShift)) {
anim.SetInteger ("isWalking", 1);
}
}
}
I am using the default controller for the movement itself (the one that comes in the standard assets). In advance, thank you, if someone can help me.
Answer by IsaiahKelly · Sep 09, 2017 at 11:53 PM
Handle Your State in the Actual (Animator) State Machine Instead!
I think the first and most important problem here is that you're handling all your states in that script itself instead of in the animator controller, which is already a state machine designed for that exact purpose!
In the animator you can setup many different conditions to control exactly what, when and how animations play. It's a huge topic though, so I would recommend you go study up on the Animator controller more.
As for the code itself, the D key overrides the A key simply because your checking isRight after checking isLeft. Changing the order of these if conditions will change the priority. However, then you just have the oppiste problem of A overriding D, So it would be best to just add an additional check to each if statement, like this:
if (isRight == true && isLeft == false) {
anim.SetFloat("Speed", 1.5f);
anim.SetInteger ("isWalking", 1);
}
But all these conditions should actually be controlled in the animator controller itself.