#Consistent jump hight in 2D platformer (changing gravity)

1 messages · Page 1 of 1 (latest)

quartz ridge
#

Hello there, I'm currently working on a 2D game, i want the game to be snappy and have all the "good" features. That means I want my gravity slightly increased/decreased when jumping.

But I cant figure out how much AddForce, on impulse to add so the jump height is always consistent, when the gravity is changing.

#
private void setGravity() { // some physics formula for calculating gravity
    Vector2 newGravity = new Vector2(0, (-2 * jumpHeight) / (jumpApexTime * jumpApexTime));
    _RB2D.gravityScale = (newGravity.y / Physics2D.gravity.y) * defaultGravityMultiplier;
}

private void changeGravity() {
    if (_RB2D.velocity.y > verticalVelocityEpsilon) {
        if (_groundCheck.isGrounded) {
            defaultGravityMultiplier = defaultGravity; // Reset the gravity multiplier, or if we are standing on something that is moving
        } else {
            defaultGravityMultiplier = upwardGravityMultiplier; // No variable Jump Height
        }
    } else if (_RB2D.velocity.y < -verticalVelocityEpsilon) {
        if (_groundCheck.isGrounded) {
            defaultGravityMultiplier = defaultGravity; // Reset the gravity multiplier, or if we are standing on something that is moving
        } else {
            defaultGravityMultiplier = downwardGravityMultiplier; // 
        }
    } else { 
        if (_groundCheck.isGrounded) {
            isJumping = false;
        }
        defaultGravityMultiplier = defaultGravity;
    }

    // add hang time?
}

private void CalculateJumpForce() {
    jumpForce = Mathf.Sqrt(-2f * Physics2D.gravity.y * _RB2D.gravityScale * jumpHeight);
    jumpForce = jumpForce - _RB2D.velocity.y;
}

private void jump() {
    if (_groundCheck.isGrounded || (airJumpCounter < maxAirJumps) || (coyoteTimeCounter < coyoteJump && coyoteTimeCounter > 0.03f)) {
        _input.intendedJump = false;
        jumpBufferCounter = 0;
        coyoteTimeCounter = 0;

        CalculateJumpForce();
        _RB2D.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);

        airJumpCounter++;
        isJumping = true;
    }
}