I’ve been learning how to create a 2D character and use the animator, and things have been going pretty well, u n t i l it came to figuring out how to make an animation only active when in the air. Here is the Animator script for reference:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterAnim : MonoBehaviour {
private Animator anim;
private PlayerController controller;
void Start(){
anim = GetComponent<Animator> ();
}
void Update(){
if (Input.GetKey (KeyCode.LeftArrow) || Input.GetKey (KeyCode.RightArrow)) {
anim.SetBool("isRunning", true);
} else {
anim.SetBool ("isRunning", false);
}
if (Input.GetKeyDown (KeyCode.UpArrow)) {
anim.SetTrigger("jump");
}
if (controller.isGrounded) {
anim.SetBool ("isJumping", true);
}
}
}
And, in case it may be needed, here’s the Player Controller Script for reference as well:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float speed;
public float jumpforce;
private float moveInput;
private Rigidbody2D rb;
private bool facingRight = true;
private bool isGrounded;
public Transform groundCheck;
public float checkRadius;
public LayerMask whatIsGround;
private int extraJumps;
public int extraJumpValue;
void Start(){
extraJumps = extraJumpValue;
rb = GetComponent<Rigidbody2D> ();
}
void FixedUpdate(){
isGrounded = Physics2D.OverlapCircle(groundCheck.position, checkRadius, whatIsGround);
moveInput = Input.GetAxis ("Horizontal");
rb.velocity = new Vector2 (moveInput * speed, rb.velocity.y);
if (facingRight == false && moveInput > 0) {
Flip ();
} else if (facingRight == true && moveInput < 0) {
Flip ();
}
}
void Update(){
if (isGrounded == true) {
extraJumps = extraJumpValue;
}
if (Input.GetKeyDown (KeyCode.UpArrow) && extraJumps > 0) {
rb.velocity = Vector2.up * jumpforce;
extraJumps--;
} else if (Input.GetKeyDown (KeyCode.UpArrow) && extraJumps == 0 && isGrounded == true) {
rb.velocity = Vector2.up * jumpforce;
}
}
void Flip(){
facingRight = !facingRight;
Vector3 Scaler = transform.localScale;
Scaler.x *= -1;
transform.localScale = Scaler;
}
}