Jumping perpendicular to the surface

Hi everyone!
I want to jump perpendicular to the surface as I demonstrated in the image. When I jump, it goes backward. How can I fix this? Thank you!

Here is the current status.
alt text
Here is what I want.

Jumping method.

public void Jump()
    {
        if (isGrounded)
        {
            rb.AddForce(new Vector2(0, 1) * jumpSpeed, ForceMode2D.Impulse);
            isGrounded = false;
        }
    }

Currently, you point the jump force in the y-World Direction. What you want is to point the jump in the direction of the normal of the surface.

If you can guarantee that the boxes have their axis always pointed relative to the surface (local +x-axis = forward, local +y-axis = up) you can use the up Vector of their transform.

rb.AddForce(transform.up * jumpSpeed, ForceMode2D.Impulse);

If you can not guarantee that, e.g. because they rotate at some point, you need to create a more complex solution with raycasts. You could raycast in all 4 directions (up, down, left, right) and use the closest hit with the surface. This hit gives you the normal of the surface, which would serve as your up axis of the jump.

RaycastHit2D raycastHit2D = Physics2D.Raycast(transform.position, direction);
rb.AddForce(raycastHit2D.normal * jumpSpeed, ForceMode2D.Impulse);

But beware, this proposed solution is not edge case proof, especially when your box is not laying flat on the ground or in some kind of curve

Maybe you could also work with OnCollisionStay and use the ContactPoints for the direction of the raycast, to prevent or minimize the edge case further.