Making the mushroom patrol requires scripting.
Making the mushroom patrol requires scripting.
Add a Script to the Mushroom
Add a Script to the Mushroom
Uncheck the option for Template
Uncheck the option for Template
So we begin with an Empty Script
So we begin with an Empty Script
Save it as mushroom.gd
Save it as mushroom.gd
Add a constant to control the speed of the mushroom
Add a constant to control the speed of the mushroom
Add a variable for the direction
Add a variable for the direction
Add a variable for the health points
Add a variable for the health points
Create a function to add gravity to the level
Create a function to add gravity to the level
If the enemy is not on the ground
If the enemy is not on the ground
they should be pulled towards the ground
they should be pulled towards the ground
Note that the get_gravity() function is part of the CharacterBody2D class
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
It fetches or returns the value of the world gravity variable which can be found in
Project --> Project Settings --> General --> Physics --> 2D --> Default Gravity
Project --> Project Settings --> General --> Physics --> 2D --> Default Gravity
Create a function to move the mushroom
Create a function to move the mushroom
Move right by multiplying the SPEED by the direction
Move right by multiplying the SPEED by the direction
Create a function to reverse direction
Create a function to reverse direction
if the mushroom hits a wall
if the mushroom hits a wall
invert the direction variable
invert the direction variable
Call these functions in _physics_process
Call these functions in _physics_process
Note that it is essential to call reverse_direction AFTER move_and_slide
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.
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
Save your Mushroom scene
Put a Mushroom in your level
Put a Mushroom in your level
Test that it bounces back and forth between walls
Test that it bounces back and forth between walls
If you place mushrooms on platforms
If you place mushrooms on platforms
They will fall off the edge
They will fall off the edge
We will make the mushroom
We will make the mushroom
patrol the platform in the next section.
patrol the platform in the next section.