C# Challenge - Controlling Rigidbody Gravity
Ever played a game with a trap door which let’s you conveniently fall down and you can’t do anything about it? Lucky you, then!
Today’s challenge is kind of the same. Let’s take a look at it!
Okay, let’s break down the task:
- When the player hits the space key, enable gravity on the Rigidbody and turn the mesh renderer of the floor red
- As soon as the player triggers a collision with the floor, turn the mesh renderer of the floor blue and destroy the player
So, basically, all we need to do is creating two methods which will handle exactly that for us!
I. Getting started - The variables
We just need two variables this time. We need to manipulate the gravity on the Rigidbody and change the material color of the MeshRenderer.
That being said, we need one handle for the Rigidbody, and another handle for the MeshRenderer:
Because the script is attached on the player, we simply need to grab the Rigidbody component from it. As we want to change the material’s color of the Floor, we need to search for that GameObject first and grab the compjnent afterwards.
II. Let the player fall!
When the player hits the Space key, the sphere, representing the player, shall fall down. There are two ways to fin d out how to do that:
- Do a research on the internet
- Try your luck with IntelliSense or the code suggestions inside your IDE
The good thing about Unity is its hierarchical access system. We know that we want to manipulate something on the Rigidbody. Simply typing out the variable and the . will trigger IntelliSense which can help you in a quick way:
This time, it was pretty easy to figure out what every point is doing, as they are pretty self-explanatory. As we want to manipulate the gravity, useGravity is the thing we need!
We want to enable gravity, and as the tooltip tells us, useGravity is of typoe bool. Setting it to true will do the trick here and give us the behavior we are expecting!
III. Turning the floor blue
The next thing to do now is to change the floor color to red, as soon as the player begins to fall! We already assigned the MeshRenderer to a variable. To manipulate the color, we need to access the MeshRenderer’s material and change the color of it.
Running the program now, will show us the following:
IV. Changing the color at collision
One part of the task is to change the floor color to blue when the player collides with it.
To detect trigger collisions, we use Unitys OnTriggerEnter() method. And as we just changed the color of the floor, we know what we have to do already!
Here are the results:
V. Destroying the player
The last thing to do is to destroy the player GameObject right after the color of the floor has been changed.
This can be achieved by adding just one line of code into the method:
VI. The end result and full code
Here is the end result with everything working:
And as promised, here is the full code for this challenge, including the pseudo-code: