How to make objects float

Hello,
I want to implement small floating islands for my sidescroller, that one can jump on.
I started with counteracting gravity with

void FixedUpdate()
{
    rb.AddForce(-Physics.gravity);
}

And the island floated, but when I jump on it, it will of course just lose height forever, because I only counteract the gravity that acts on the mass of the island, not island+player.

So I somehow need a force that always acts in the direction of the Islands origin.
I tried adding a force that depends on the distance of the islands position and its origin.
That kind of works, but the island will never again stop moving up and down again.

What can I do to achieve my goal?

Edit: I forgot to mention that I want my island to float in air, not in water, so I have to work my way around physics, as that shouldn’t be possible in the real world.

What you need is to implement bouyancy. The force to apply to the object depends on the amount of water displaced by the object at any one time.

If your object has a complex shape, it will be difficult to exactly determine its volume. Therefore, it’s probably better to try to estimate its density and its mass. For example, for a person, it’s relatively easy to arrive at a reasonable volume because we can assume that a person’s density roughly matches that of water, and we’re quite good at estimating approximate mass of a human. Given those two numbers, it’s trivial to arrive at the volume.

The tricky part is to come up with a way to handle the situation where the object is only partially submerged, because obviously, a partially submerged object only displaces water equal to some fraction of its volume. So there is an equilibrium there, where the mass of a volume of water equal to some fraction of the object’s volume exactly equals the mass of the submerged portion of the object. And that’s the sweet spot where the object can come to rest floating.

See the linked Wikipedia article for more information.

Hey dude, What’s up!

CHPedersen is right. Bouyancy is the answer. And unity has the perfect tool for that.

Check this out.

SpringJoint2D. I think that’s what you need. A helper recommended this to me when I was trying to do an effect for a Water Spout when a GameObject is weighing on it.

Worked fine for me.

Hope it helps man!

Your islands should not have any Rigidbodies, they need only Colliders. This way the islands won’t move and the player can still jump on them.