Setting up a Ray Cast

For the mushroom to stay on the platform

it must have some way to detect the edge

We can do this with a RayCast2D

A RayCast is a ray cast out to find the first object

it collides with in the direction it was sent.

It may be the case that it doesn't collide with anything.

Add a RayCast2D node as a child of the Mushroom.

We want the Ray to detect when it is no longer on the floor

So place at the bottom of the mushroom, to the right.

The Ray should be looking for collisions on the ground and pass_through layers so turn on Mask 2 and 3.

Scripting the Ray

In the Mushroom Script

Add a function called platform_edge()

In it, check if the Ray is NOT colliding

This means there is no platform below it

So reverse the direction of the mushroom

and move the Ray to check the opposite side.

Call this function in _physics_process

Now mushrooms which are on floating platforms

Will patrol the platform and not fall off.