Alternate ladder solution

Submitting this as a “Show” but would actually appreciate feedback too.

This solution doesn’t adjust GravityScale, but instead freezes and unfreezes the Rigidbody constraints. It allows gravity to affect climb speed (slower to climb up, but faster to “slide” down). It also has some checks for if the player is moving “through” the ladder (while jumping, for instance) and allows them to do so freely. The player can jump off the sides of the ladder, but can’t jump “up” it (there has to be horizontal movement, similar to classic Mega Man games).

All that said, it feels like spaghetti code to me. It works, but I can’t help but feel it could be a lot more efficient. Any thoughts are welcome!

    private void Climb()
    {
        if (!myCollider2D.IsTouchingLayers(LayerMask.GetMask("Ladders"))) 
        {
            return; 
        }

        if (moveInput.y != 0)
        {
            UnFreeze();
            Vector2 climbVelocity = new Vector2(myRigidbody2D.velocity.x, moveInput.y * climbSpeed);
            myRigidbody2D.velocity = climbVelocity;
        }
        else if (moveInput.x != 0)
        {
            UnFreeze();
            return;
        }
        else
        {
            Freeze();
        }
    }

    private void Freeze()
    {
        myRigidbody2D.constraints = RigidbodyConstraints2D.FreezeAll;
    }

    private void UnFreeze()
    {
        myRigidbody2D.constraints = RigidbodyConstraints2D.None;
        myRigidbody2D.constraints = RigidbodyConstraints2D.FreezeRotation;
    }
1 Like

Privacy & Terms