I have an issue with double jump for the player my code is working but I want the second double jump animation finish(idle Animation: anim.SetBool("Jump", false)] before he touches the ground can anyone help me on that here is my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private Animator anim;
private float speed = 5f;
private Rigidbody2D myBody;
public Transform groundCheckPosition;
public LayerMask groundLayer;
private bool isGrounded;
private bool jumped;
private float jumpPower = 5f;
private bool doubleJump;
void Start()
{
myBody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
isGrounded = false;
jumped = false;
doubleJump = false;
}
// Update is called once per frame
void Update()
{
PlayerJump();
}
private void FixedUpdate()
{
CheckIfGrounded();
PlayerWalk();
}
void PlayerWalk()
{
float h = Input.GetAxisRaw("Horizontal");
if (h > 0)
{
anim.SetInteger("Speed", (int)speed);
ChangeDirection(1);
}
else if (h < 0)
{
anim.SetInteger("Speed", (int)speed);
ChangeDirection(-1);
}
else
{
anim.SetInteger("Speed", 0);
}
myBody.velocity = new Vector2(h * speed, myBody.velocity.y);
}
void ChangeDirection(int direction)
{
var temp = transform.localScale;
temp.x = direction * (0.8f);
transform.localScale = temp;
}
void CheckIfGrounded()
{
if (!Physics2D.Raycast(groundCheckPosition.transform.position, Vector2.down, 0.1f, groundLayer))
{
isGrounded = false;
}
else
{
isGrounded = true;
doubleJump = false;
}
if (isGrounded)
{
jumped = false;
anim.SetBool("Jump", false);
}
}
void PlayerJump()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if ((isGrounded && !jumped) || (!doubleJump && !isGrounded))
{
jumped = true;
doubleJump = true;
myBody.velocity = new Vector2(myBody.velocity.x, jumpPower);
anim.SetBool("Jump", true);
}
}
}
}//class
Edit
I have changed the code from that :
void Update()
{
PlayerJump();
}
private void FixedUpdate()
{
CheckIfGrounded();
PlayerWalk();
}
to that :
void Update()
{
}
private void FixedUpdate()
{
CheckIfGrounded();
PlayerJump();
PlayerWalk();
}
I have changed it because FixedUpdate, we use it only for physics because it's not called every frame, unlike update function.
the problem is that the double jump doesn't work in this case can you explain me why?