SteamVR: Handling Vive Controller Input Part 2

Rushil Reddy

Following from our previous tutorial on how to map your controllers we are now going to learn how to make your gun actually shoot.

Our first step is to create an actual bullet that will fire once we press the trigger.

Download the bullets from the asset store(search for AMMO Types and sort by free) and import it.

Now, drag a copy of the imported prefab into your scene. In the inspector tab, click Add Component>Rigidbody and make sure Use Gravity is unchecked. Rename it to bullet and then drag it back to your project tab to save it as a new prefab.

Click the one of the guns in your scene and in the hierarchy tab right click and create an empty game object. Name it bulletSpawn and use the provided transform tools to move it to the end of the guns barrel.

Now open the ControllerManager script we created in the last tutorial and add in these lines

public Rigidbody bulletPrefab;

public Transform firePosition;

void Update(){

     Debug.Log(“Fire”);

     Rigidbody bulletInstance;

     bulletInstance = Instantiate (bulletPrefab, firePosition.position, firePosition.rotation) as Rigidbody;

     bulletInstance.AddForce (firePosition.forward * 2000);

}

Now, go back to the editor and while you have the gun selected, drag the bulletSpawn gameObject into the scripts firePosition opening(which should be on the bottom right). Do the same with the bullet prefab you created from the project tab to the inspector. Repeat these steps for the gun assigned to your other controller.

Hit Play and your guns should now be shooting bullets with trigger presses.