So I wanna play my jump animation when the player is the air and when he presses space ONCE. It may sound simple but I can’t figure out how to do this at all. Here’s my code:
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
//private variables
private Rigidbody2D rb;
bool IsGrounded = false;
//public variables
public float speed;
public float jumpForce;
public Transform GroundChecker;
public float GroundRadius;
public LayerMask GroundLayer;
public float fallMultiplier = 2.5f;
public float lowJumpMultiplier = 2f;
public SpriteRenderer playerSprite;
public Animator playerAnimator;
void Start()
{
Input.GetAxisRaw("Horizontal");
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Move();
Jump();
CheckForGround();
BetterJump();
AnimateSprite();
}
void Move()
{
float xHor = Input.GetAxisRaw("Horizontal");
float MoveDir = xHor * speed;
rb.velocity = new Vector2(MoveDir, rb.velocity.y);
}
void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && IsGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, jumpForce);
}
}
void CheckForGround()
{
Collider2D collider = Physics2D.OverlapCircle(GroundChecker.position, GroundRadius, GroundLayer);
if (collider != null)
{
IsGrounded = true;
}
else
{
IsGrounded = false;
}
}
void BetterJump()
{
if (rb.velocity.y < 0)
{
rb.velocity += Vector2.up * Physics2D.gravity * (fallMultiplier - 1) * Time.deltaTime;
}
else if (rb.velocity.y > 0 && !Input.GetKey(KeyCode.Space))
{
rb.velocity += Vector2.up * Physics2D.gravity * (lowJumpMultiplier - 1) * Time.deltaTime;
}
}
void AnimateSprite()
{
if (Input.GetKey(KeyCode.A))
{
playerSprite.flipX = true;
playerAnimator.Play("Run");
}
else if (Input.GetKey(KeyCode.D))
{
playerSprite.flipX = false;
playerAnimator.Play("Run");
}
else
{
playerAnimator.Play("Idle");
}
}
}
Please bear with my messy code.