I
I
Ilya Famin2021-04-30 18:24:46
C++ / C#
Ilya Famin, 2021-04-30 18:24:46

Why is only the rest animation playing?

The code:

private float speed = 8;
    private int lives = 5;
    private float jumpForce = 15;
    private bool isGround = false;

    private Rigidbody2D rb;
    private Animator anim;
    private SpriteRenderer sprite; 

    private void FixedUpdate(){
        CheckGround();
    }

    private void Update() {
        if (Input.GetButton("Horizontal")) {
            Run();
        }
        if (isGround && Input.GetButton("Jump")) {
            Jump();
        }
    }
    
    private States State{
        get { return(States)anim.GetInteger("state"); }
        set { anim.SetInteger("state", (int)value); }
    }

    private void Awake() {
        rb = GetComponent<Rigidbody2D>();
        anim = GetComponent<Animator>();
        sprite = GetComponentInChildren<SpriteRenderer>();
    }
    private void Run() {
        if(isGround) State = States.run;
        Vector3 dir = transform.right * Input.GetAxis("Horizontal");
        transform.position = Vector3.MoveTowards(transform.position, transform.position + dir, speed * Time.deltaTime);
        sprite.flipX = dir.x < 0.0f;
    }
    private void Jump() {
        rb.AddForce(transform.up * jumpForce);
    }
    private void CheckGround(){
        Collider2D[] collider = Physics2D.OverlapCircleAll(transform.position, 0.3f);
        isGround = collider.Length > 1;
        if(!isGround) State = States.jump;
    }
}
public enum States{
    Idle, run, jump
}

State fields in Unity: 0 - Rest, 1 - Run, 2 - Jump

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question