Here, we will create ways for the player to interact with the game world. For our game, we will have the player shooting their gun, collecting potions, and pausing the game as interactions. Create a new C# script and name it PlayerInteraction
. First, we will create a couple of variables and add them to our script:
public GameObject Projectile, Potion;
The Projectile
GameObject will be the bullets that we shoot and the Potion
GameObject will be the potion prefab that we created earlier.
We will create the functionality to shoot the gun and pause the game. Add this Update
function to your script:
void Update () { if(Time.tmeScale != 0.00f) { if(Input.GetButtonUp("Fire1")) Instantiate(Projectile, transform.position, transform.rotation); if(Input.GetButtonUp("Esc_Key")) { if(Time.timeScale != 0.00f) Time.timeScale = 0.00f; else Time.timeScale = 1.00f; } } }
The first if
statement will allow the player to shoot the projectile. To shoot it, we instantiate the GameObject and the player's location and rotation. To let the player pause the game, use an input that we created in Chapter 1, Interactive Input. Setting the timeScale
object to 0
will pause any script that uses the Update
function, and setting it to 1
will resume it.
To collect potions, we will need to add a collision function, as follows:
void OnTriggerEnter(Collider other) { if(other.tag == "Potion") { GetComponent<Inventory>().AddToInventory(1, Potion); for(int i = 0; i < GetComponent<GUI_2D>().Items.Count; i ++) { if(GetComponent<GUI_2D>().Items[i].name == "") GetComponent<GUI_2D>().Items[i] = Potion; break; } Destroy(other.gameObject); } }
To collect the potion, we check the trigger's tag to make sure it is the potion. Next, we add it to the inventory by calling the AddToInventory
function of the Inventory
component, which we will be adding later. Also, we add it to the GUI by calling the Items
array from the GUI_2D
component and assigning the potion. Finally, we destroy the GameObject
potion in the game world so that the player can no longer get that potion.
3.133.134.17