Coyote Timer Gives Double Jump Frames.
Hi everyone! I'm kinda' new to C# and codes in general and I'm having an issue with the CoyoteJump effect, where I seem to get frames where the player can get an extra jump. Can someone help me out? Thanks <3 Here is my code so far ( i know it's not the cleanest).
[SerializeField] private LayerMask platformLayerMask;
[Range(1, 10)]
public float jumpVelocity;
bool jumpRequest;
private Rigidbody2D rb;
private BoxCollider2D boxCollider2d;
private Animator anim;
private float coyoteTimer;
private float coyoteFrames =20;
void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
boxCollider2d = transform.GetComponent<BoxCollider2D>();
}
void Update()
{
if (Input.GetButtonDown("Jump"))
{
jumpRequest = true;
anim.SetTrigger("takeOf");
}
}
void FixedUpdate()
{
if (IsGrounded() == true)
{
anim.SetBool("isJumping", false);
coyoteTimer = 0;
}
else
{
anim.SetBool("isJumping", true);
coyoteTimer++;
}
if (jumpRequest == true && coyoteTimer < coyoteFrames)
{
rb.velocity = Vector2.up * jumpVelocity;
jumpRequest = false;
}
}
private bool IsGrounded()
{
float extraHeightText = 0.1f;
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider2d.bounds.center, boxCollider2d.bounds.size, 0f, Vector2.down, extraHeightText, platformLayerMask);
return raycastHit.collider != null;
}
}
Answer by Marioooo · Apr 11, 2021 at 06:09 PM
i think there's a tiny problem with how do you calculate the coyote timer...
Update Method runs once a frame... every frame...
Fixed update method... runs 50 times each frame...
BUT: the coyote timer as the name says is a timer... not all pcs will run the game at the same speed... some will be 60fps other will be 120fps and other 10fps... slow pc's will have more "coyote time" and faster pc's will have less of it...
the right way to achieve this is to make the timer to run inside Update and usibg a time measurement, (in seconds) and not in frames...
Inside update do a
coyoteTimer += Time.deltaTime;
this way the coyote timer will be measured in seconds (being 1 a second, so change that 20 casuse will be 20 seconds)
then after you jump, disable the coyote jump with a boolean... to prevent new jumps
hope this helps