Making the mushroom patrol requires scripting.



Add a Script to the Mushroom

Uncheck the option for Template

So we begin with an Empty Script

Save it as mushroom.gd

Add a constant to control the speed of the mushroom

Add a variable for the direction

Add a variable for the health points

Create a function to add gravity to the level

If the enemy is not on the ground

they should be pulled towards the ground

Note that the get_gravity() function is part of the CharacterBody2D class

It fetches or returns the value of the world gravity variable which can be found in

Project --> Project Settings --> General --> Physics --> 2D --> Default Gravity

Create a function to move the mushroom

Move right by multiplying the SPEED by the direction

Create a function to reverse direction

if the mushroom hits a wall

invert the direction variable

Call these functions in _physics_process

Note that it is essential to call reverse_direction AFTER move_and_slide

If you try to reverse direction before calling move_and_slide(), the engine hasn't yet checked for collisions in the current frame, so it doesn’t know whether the enemy has hit a wall.

Save your Mushroom scene

Put a Mushroom in your level

Test that it bounces back and forth between walls

If you place mushrooms on platforms

They will fall off the edge

We will make the mushroom

patrol the platform in the next section.