Instant Thruster Recharger- Game Dev Series 38
Objective: Create a visualize rechargeable thruster easily.
To create a visualize thruster charger, I will use Slider of UI as a command to control the speed of Player.
In this article, there are 2 parts to create this function.
- Create a thruster Slider in UI, and make it recharge and discharge with time.
- Control the player speed according to different state of Slider.
Create thruster Slider
Right click on Canvas, then select UI> Slider.
Adjust the position and scale. You can disable the handle gameobject under the Slider gameobject. We don’t need the handle in this one.
Set the min & max value which we will use it later.
You might notice there is a tiny gap on the slider when you remove the handle. To erase this, click Fill Area under Slider gameobject, and set the Left & Right to same amount, your slider should looks great.
Then we can make it recharge by time.
Open UIManager script, create a variable of slider, and set the value of slider to 0 at Start().
In the Update(), make it auto-recharge by the code below. We also need another bool variable.
Back to editor, drag Slider to the variable. Play the game and you should see the Slider is charging now.
In the Update(), we have already got one line to decrease the slider. However, we don’t have any trigger to decrease it yet.
This is where we need to let our Player to control the Slider.
Create another public method that the Player could call.
With this method, when Player call it, the bool would become true and our Slider value will decrease as in Update().
Now within Player script, add an if statement inside the Update().
With this statement, if we press left shift, the slider will decrease. Let’s check if this works.
You might notice the problem. The value decrease every time I pressed shift, which is not we want.
We want to enable thruster only when it is fully loaded. In that case, we can simply add an if statement to ThrustTrigger().
And now we can call back to Player to engage the thruster.
Controlling the speed
To control the speed, we need to set 2 variables in Player.
- _originSpeed: This will storage the origin speed of our Player in Start().
- _thrusterSpeed: This is what we are going to set a new float as the thruster speed.
With these variables, we can create another public method to switch the speed.
This is a switch to enable the thruster. It requires a bool to the statement. We can call it in out UIManager().
And don’t forget to disable the thruster when the value of Slider is 0.
All ready. You can test drive now!