Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My getkeydown is not being recognized

Tags:

c#

unity3d

Hey its a simple script whit animation params , but I don't know why my if with getkeydown is not executing! Its suppose to play an idle animation if key is not being pressed but thats not happening instead its just not going trough that part of the code.

public class PlayerMovement : MonoBehaviour {

private Rigidbody2D rigidbodyMurrilo;
public float speed;
public Animator anim;
public bool FacingRigth;
public Transform transform;

private void Start()
{
    rigidbodyMurrilo = GetComponent<Rigidbody2D>();
    anim = GetComponent<Animator>();

    FacingRigth = true;

}

void FixedUpdate()
{
    float horizontal = Input.GetAxis("Horizontal");
    float vertical = Input.GetAxis("Vertical");

    HandleMovement(horizontal);

    Flip(horizontal);




}

void HandleMovement(float horizontal)

{
    rigidbodyMurrilo.velocity = new Vector2(horizontal * speed, rigidbodyMurrilo.velocity.y);

}


private void Update()
{
    if (Input.GetKeyDown("d") || Input.GetKeyDown("left") || Input.GetKeyDown("a") || Input.GetKeyDown("rigth"))
    {
        anim.Play("MoveRigth");
    }

    Debug.Log(Input.GetKey("d"));

    if (Input.GetKeyUp("d") || Input.GetKeyUp("left") || Input.GetKeyUp("a") || Input.GetKeyUp("rigth"))
    {
        anim.Play("Idle");
    }
}

private void Flip (float horizontal){

    if(horizontal > 0 && !FacingRigth || horizontal<0 && FacingRigth)
    {

        Vector3 theScale = transform.localScale;

        theScale.x *= -1;

        transform.localScale = theScale;

        FacingRigth = !FacingRigth;

    }

}
like image 261
Pedro Gouveia Avatar asked Jul 08 '18 12:07

Pedro Gouveia


1 Answers

The reason for this is because the Input.GetKeyUp() method don't work the way you think it does :). The Input.GetKeyUp() works like that:

The method returns true during the frame the user releases the key identified by name.

I suggest you to rework your if statement like that:

    if (Input.GetKeyDown("d") || Input.GetKeyDown("left") || Input.GetKeyDown("a") || Input.GetKeyDown("rigth"))
    {
        anim.Play("MoveRigth");
    } 
    else 
    {
        anim.Play("Idle");
    }

or just use the same statement the second time with ! in front of it. I hope this helps :)

like image 132
Ivan Kaloyanov Avatar answered Oct 26 '22 14:10

Ivan Kaloyanov