Part 17 - Keyboard input - Fire.

By Jamie Chatterton / 2018-06-12

So I guess first thing? Instead of dropping every second… how about when the user presses a key?

Unity abstracts input into an object called, well, Input. The idea being that you map the Keyboard, Mouse, Touch Screen, VR devices, whatever, into virtual devices that have a defined range and reaction.

There is a default setup for this mapping, and to see it go to Edit > Project Settings > Input

This will open the InputManager in the Inspector. This has a single collapsed Axes object, opening it up shows all the different parts to it.

Our interest for now is the Fire1, opening the first one you can see it's mapped to "left ctrl" via the "Positive Button". Open the second Fire1` it's mapped to a real joystick button if one is connected too!

This "Fire1" is what we refer to when determining if it is pressed or held.

We do this via one of the functions

Input.GetButton( buttonName )
Input.GetButtonDown( buttonName )
Input.GetButtonUp( buttonName )

Where buttonName is that button name, and the three functions are

GetButton - returns true if that button is held

GetButtonDown - returns true if the button has been pressed down

GetButtonUp - returns true if the button has been released

There is no 'pressed' so I generally go for the GetButtonUp as it implies the Down and a full press cycle has been done.

So, in the Update function of SpawnerController we want to add a new coin if the Fire1 button is pressed, instead of the time. The change to the Update function turns it into…

void Update () {

	if (Input.GetButtonDown("Fire1")) {
		SpawnObject();
	}

}

If we run the game now, pressing the "left-ctrl" will add a coin, still randomly.

We should now stop it being random.

In the SpawnObject, we just want to remove the Random function, removing that entire section that is updating the locationPosition and leaving the newly Instantiated coin alone, so it just becomes what it was before…

void SpawnObject() {
	Instantiate(ObjectToSpawn, transform);
}

We can also remove the startTime private field from the class, and remove the instantiation from the Start function, as it's no longer needed.

We can now add coins as we want, in the same position, and go stupid with it...

More posts in this series.