left-shift key is pressed.
The added feature is to double speed of the player object (the spaceship) when the left shift key is pressed down. Release the speed to return to the slower speed.
Currently in this example, there are two variables in the Player.cs file which hold values for this added function.
(…Yes, the key choice could be a variable, but not in this example)
public class Player : MonoBehaviour
{
...
[SerializeField]
private float _speedMultiplier = 2.0f;
...
private bool _leftShiftSpeed = false;
...
}
The _speedMultiplier variable is already in the Unity user interface and visible for runtime adjustment using [SerializeField].
Now look at how the Input.GetKeyDown() is used in the Update() method:
public class Player : MonoBehaviour
{
...
void Update()
{
CalculateMovement();
if (Input.GetKeyDown(KeyCode.LeftShift) && (!_leftShiftSpeed))
{
Debug.Log("Left Shift down down");
_speed *= _speedMultiplier;
_leftShiftSpeed = true;
}
...
}
&& (and)
_leftShiftSpeed starts out set to false. If the key is down and
_leftShiftSpeed is not on yet, (T) and (! F), then:
Optionally post a message.
Change the speed, set _leftShiftSpeed to true.
…when the key is released, Input.GetKeyDown() returns a false.
As a review, here is the CalculateMovement() method code showing how the _speed variable is used.
public class Player : MonoBehaviour
{
...
void CalculateMovement()
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
position = new Vector3(horizontalInput, verticalInput, 0);
transform.Translate(position * _speed * Time.deltaTime);
transform.position = new Vector3(transform.position.x, Mathf.Clamp(transform.position.y, _bottomEdge + 0.5f, 0), 0);
if (transform.position.x >= _rightEdge)
{
transform.position = new Vector3(_leftEdge, transform.position.y, 0);
}
else if (transform.position.x <= _leftEdge)
{
transform.position = new Vector3(_rightEdge, transform.position.y, 0);
}
}
...
}