Untitled

 avatar
louis
plain_text
2 months ago
2.6 kB
1
Indexable
Never
 private float horizontal;
 private float speed = 8f;
 private float jumpingPower = 16f;
 private bool isFacingRight = true;

 private bool isJumping;

 private float coyoteTime = 0.2f;
 private float coyoteTimeCounter;

 private float jumpBufferTime = 0.2f;
 private float jumpBufferCounter;

 [SerializeField] private Rigidbody2D rb;
 [SerializeField] private Transform groundCheck;
 [SerializeField] private LayerMask groundLayer;

 public int maxJumps = 3;
 public int remainingJumps;


 private void Update()
 {
     horizontal = Input.GetAxisRaw("Horizontal");

     if (IsGrounded())
     {
         coyoteTimeCounter = coyoteTime;
     }
     else
     {
         coyoteTimeCounter -= Time.deltaTime;
     }

     if (Input.GetButtonDown("Jump"))
     {
         jumpBufferCounter = jumpBufferTime;
     }
     else
     {
         jumpBufferCounter -= Time.deltaTime;
     }

     if (coyoteTimeCounter > 0f && jumpBufferCounter > 0f && !isJumping)
     {
         rb.velocity = new Vector2(rb.velocity.x, jumpingPower);

         jumpBufferCounter = 0f;

         StartCoroutine(JumpCooldown());
     }

     if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
     {
         rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);

         coyoteTimeCounter = 0f;
     }


     if (IsGrounded() && !Input.GetButton("Jump"))
     {
         isJumping = false;
         remainingJumps = maxJumps;
     }



     if (Input.GetButtonDown("Jump"))
     {
         if (IsGrounded() || (isJumping && remainingJumps > 0))
         {
             isJumping = true;
             rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
             remainingJumps--;
         }
     }

     if (Input.GetButtonUp("Jump") && rb.velocity.y > 0f)
     {
         rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
     }

     Flip();
 }

 private void FixedUpdate()
 {
     rb.velocity = new Vector2(horizontal * speed, rb.velocity.y);
 }

 private bool IsGrounded()
 {
     return Physics2D.OverlapCircle(groundCheck.position, 1f, groundLayer);
 }

 private void Flip()
 {
     if (isFacingRight && horizontal < 0f || !isFacingRight && horizontal > 0f)
     {
         Vector3 localScale = transform.localScale;
         isFacingRight = !isFacingRight;
         localScale.x *= -1f;
         transform.localScale = localScale;
     }
 }

 private IEnumerator JumpCooldown()
 {
     isJumping = true;
     yield return new WaitForSeconds(0.4f);
     isJumping = false;
 }
Leave a Comment