I took “ApplyJumpForce()” out of “OnJump” because I wasn’t sure how to pass through a parameter to the “OnJump” action. I wanted to set different jump strengths for the first and second jumps. I figure it’s okay to in this situation because ApplyJumpForce() is in the same script as HandleJump(), but otherwise it would be good to know how to pass through parameters to Actions.
I apologise that my code is a little bit different from the course, but I’ve tested it, and it seems to be working.
private void Update()
{
GatherInput();
Movement();
CoyoteTime();
HandleJump();
HandleSpriteFlip();
}
private void FixedUpdate()
{
HandleGravity();
Land();
}
private void CoyoteTime()
{
if (CheckGrounded()) _coyoteTimer = _coyoteTime;
else _coyoteTimer -= Time.deltaTime;
}
private bool CheckGrounded()
{
Collider2D isGrounded = Physics2D.OverlapBox(_feetTransform.position,_groundCheck,0f,_groundLayer);
return isGrounded;
}
private void HandleJump()
{
if (_doubleJumpAvailable && _frameInput.Jump)
{
_doubleJumpAvailable = false;
ApplyJumpForce(_doubleJumpStrength);
OnJump.Invoke();
return;
}
if (!_isJumping && _coyoteTimer>=0 && _frameInput.Jump) {
_doubleJumpAvailable = true;
_isJumping = true;
ApplyJumpForce(_jumpStrength);
OnJump.Invoke();
return;
}
if (!_isJumping && _coyoteTimer < 0)
{
_doubleJumpAvailable = true;
_isJumping = true;
return;
}
}
private void ApplyJumpForce(float jumpStrength)
{
if(_rb.velocity.y<0) _rb.velocity = new Vector2(_rb.velocity.x, 0f);
_rb.AddForce(Vector2.up * jumpStrength, ForceMode2D.Impulse);
_rb.gravityScale = _risingGravityScale;
}
private void HandleGravity()
{
if (!_isJumping) _rb.gravityScale = _normalGravityScale;
else if (_rb.velocity.y > _hangVelovityThreshold && _frameInput.Rise)
_rb.gravityScale = _risingGravityScale;
else if (_rb.velocity.y > -_hangVelovityThreshold && _frameInput.Rise)
_rb.gravityScale = _hangGravityScale;
else _rb.gravityScale = _normalGravityScale;
}
private void Land()
{
if (_isJumping && _rb.velocity.y < 0.01 && CheckGrounded()) {
_rb.gravityScale = _normalGravityScale;
_isJumping = false;
_doubleJumpAvailable = false;
}
}