2D Galaxy Shooter P1: Adding Speed Thrusters!
For today’s challenge, I implemented thrusters!
Thrusters give us the ability to boost our speed when holding down the left shift key.
Since I knew that we want to control the logic with a bool in the Player script, I initialized and declared:
private bool _isThrusting = false;
I also knew that we want a variable for the speed when thrusting:
[SerializeField] private float _thrustSpeed = 3;
Therefore, I went ahead with adding the Input logic in the Update()
function:
if(Input.GetKey(KeyCode.LeftShift) && !_isThrusting)
{
_isThrusting = true;
}
else
{
_isThrusting = false;
}
If the shift key is held down, activate the thruster. If it's not, then deactivate!
The next step is to make some changes to the PlayerMovement()
function. This is how it looked:
private void PlayerMovement()
{
float xInput = Input.GetAxisRaw(“Horizontal”);
float yInput = Input.GetAxisRaw(“Vertical”); Vector3 movement = new Vector3(xInput, yInput, 0); transform.Translate(movement.normalized * _speed * Time.deltaTime);
}
In bold is where I would like to adjust the speed of the player’s thrust. But I need to split it into its own condition and use _isThrusting
.
This is how it looks now:
private void PlayerMovement()
{
float xInput = Input.GetAxisRaw(“Horizontal”);
float yInput = Input.GetAxisRaw(“Vertical”); Vector3 movement = new Vector3(xInput, yInput, 0); if (_isThrusting)
{
transform.Translate(movement.normalized * (_speed + _thrustSpeed) * Time.deltaTime);
}
else if(!_isThrusting)
{
transform.Translate(movement.normalized * _speed * Time.deltaTime);
}
}
If _isThrusting
is true, then use the altered transform.Translate()
logic with the _thrustSpeed
variable. Else if _isThrusting
is false, then use the original transform.Translate()
logic without the _thrustSpeed
variable.
That is it!
For the next challenge, I will add the functionality of the thrusters depleting and having a UI element for representation.
Thank you for your time!