UnThruster: Scaling Bar HUD
Objective: Create a UI element to visualize the charge element of the thrusters!
In the current state of the game, we can use boost/sprint forever. In this tutorial I’m going to change this to a more current style of a speed boost by giving the player only 5 seconds of boost and adding a UI element to represent how much sprint the player currently has.
We are going to begin by creating a UI element, I’m using a slider.
For cosmetic reasons I delete the handle slide area and the fill.
Now position the slider where you want it and open the player script.
We need to add a few variables. A game object for the slider bar. We need to add a float for the max boost, current boost, boost left, boost drain rate, sprint speed, and normal speed. Finally, a bool for sprinting.
Under the start method set the sprint speed variable to speed times 1.5f, also set the current and max boost to 100. This way the speed boost is full when the game starts.
In the method you use to calculate your movement we need to set what boost left is. Simply put boost left is current boost divided by the max boost.
We are going to have the UI element change depending on the boost left variable.
Now we are going to completely rework the sprint code, so we are going to turn the old code into a comment.
Now we need to begin with another if statement. Inside the if statement we are going to set another limit that if our boost left is more than 0.1f then the sprinting bool will be switched to true. Else the sprinting bool will need to be set to false.
Now we need to set another if statement for if the bool is true then the speed variable needs to be set to the sprint speed. We also need to take away from the current boost my subtracting the boost drain rate Time delta Time. Else we need to call on a coroutine to handle the boost recharge.
Create an IEnumerator. Inside we need to set the current boost plus the boost drain rate times Time delta Time. Set the speed to normal speed. Inside this coroutine we need to set a max limiter for the current boost in an if statement. If the current boost gets higher than the max boost, then the current boost is equal to the max boost.
This is it. Now we have a visual representation for how much sprint the player has as well as a limit to how much boost the player can use. Don’t be afraid to experiment with your code and I’ll see you in the next tutorial.