Hello, as the title says I have a jumping bug with my 2D Character. If I hold down the space bar, he continues the jumping animation. Jump seems to be working fine other than that bug. I cannot figure out what the issue is… I think it has something to do with the code. Here is my code to the Player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField]
private float moveForce = 10f;
[SerializeField]
public float jumpForce = 11f;
private float movementX;
private float movementJump;
private Rigidbody2D myBody;
private SpriteRenderer sr;
private bool isGrounded = true;
private Animator anim;
private string RUN_ANIM = "Run";
private string GROUND_TAG = "Ground";
private string JUMP_ANIMATION = "Jump";
// Start is called before the first frame update
void Start()
{
myBody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
sr = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
PlayerMoveKeyboard();
AnimatePlayer();
PlayerJump();
}
void PlayerMoveKeyboard()
{
movementX = Input.GetAxisRaw("Horizontal");
movementJump = Input.GetAxisRaw("Jump"); // Get jump
transform.position += new Vector3(movementX, 0f, 0f) * Time.deltaTime * moveForce;
}
void AnimatePlayer()
{
// Going right
if (movementX > 0)
{
anim.SetBool(RUN_ANIM, true);
sr.flipX = false;
}
// Going left
else if (movementX < 0)
{
anim.SetBool(RUN_ANIM, true);
sr.flipX = true;
}
else
{
anim.SetBool(RUN_ANIM, false);
}
// Jump animation
if (movementJump > 0 && (movementX > 0 || movementX < 0))
{
anim.SetBool(JUMP_ANIMATION, true);
}
else if (movementX == 0 && movementJump > 0 )
{
anim.SetBool(JUMP_ANIMATION, true);
}
else
{
anim.SetBool(JUMP_ANIMATION, false);
}
}
void PlayerJump()
{
if(Input.GetButtonDown("Jump") && isGrounded)
{
isGrounded = false;
myBody.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag(GROUND_TAG))
{
isGrounded = true;
}
}
} // class
Here is a video demonstrating the bug:
