Thursday, 25 January 2018

Shooting a gun by instantiating a bullet prefab in unity game development

Hello everybody, today I’m going to be showing you how to shoot a gun by instantiating a bullet prefab. In unity, there are basically two approaches in shooting a gun either through ray casting or Instantiating a prefab. Ray casting enables you to send out an invisible rays of light usually from the center of the camera. If the rays hit something, we can gather information about what is hit and do some really cool stuff with it. More about shooting with ray casting or ray cast hit will be discuss in another tutorial. For this example, we shall be shooting a gun by instantiating a bullet. This will be in form of a first person shooter game and we shall be creating a basic sphere game object bullet. The main idea is to make the sphere game object bullet be position on the empty game object (Bullet Holder)

Note: A prefab acts as a template from which you can create new object instances in the scene. Any edits made to a prefab asset are immediately reflected in all instances produced from it but you can also override components and settings for each instance individually.




Step taken
1.      Create an empty game object and rename it to Bullet Holder position it at the mouth of the gun (i.e. the position where you want your bullet to propel out).
2.      Make the empty game object (Bullet Holder) the child of your gun. This will ensure that the gun controls the transformation settings of the empty game object
3.      Make sure that the rotation of the empty game object (Bullet Holder) is set to 0 on the x-axis, 0 on the y-axis and 0 on the z-axis.
4.      Create a c-sharp script and renamed it to bulletMovement. Populate the bulletMovement script with the following statement
using UnityEngine;
using System.Collections;

public class bulletMovement : MonoBehaviour {
            public GameObject bulletPrefab;
            private GameObject cloneBullet;
            // Use this for initialization
            void Start () {
           
            }
           
            // Update is called once per frame
            void Update () {
            if (Input.GetKey(KeyCode.F)){
                                    gunFire();
                        }
            }
            private void gunFire(){
                        cloneBullet =(GameObject) Instantiate (bulletPrefab,transform.position,transform.rotation);
                        Rigidbody rb = cloneBullet.GetComponent<Rigidbody> ();
                        rb.velocity = transform.forward * 120f;
                        Destroy (cloneBullet, 2f);
            }
}
5.      Drag the bulletMovement script to the empty game object i.e. the BulletHolder
6.      Create a new sphere game object. You can rename it if you want to. This sphere game object will act as the bullet prefab.
Add or Enable these settings in the sphere game object created earlier
i.                    Add a sphere collider
ii.                  Add a rigid body
iii.                In the rigid body disable use Gravity
7.      Drag the sphere object (bullet) to the asset folder to create a prefab (or simply you can create a prefab folder and drag the sphere object inside the prefab folder. This will make your working to be organized)
8.      Delete the sphere object (bullet) from the hierarchy view (Warning: Before deleting any game object, check if the game object has a blue text color. Any game object that is highlighted with a blue color in the hierarchy view is a prefab)
9.      Drag the bullet prefab (sphere game object ) to the empty variable field in the inspector view.
Although, it is required to use the FixedUpdate() method when physics component like rigid body are involved, but for this tutorial you can choose to used it or not to note the difference.
Firstly, we created two variables, which are the bullet prefab and the clone bullet. We use the public keyword on the bullet prefab. This will ensure that we can access it from the inspector view. We use the private keyword on the clone bullet. This is because we do not need it to appear in the inspector view.
Instantiating means to use one game object to create infinite game object. Therefore, we are instantiating the bullet prefab from the bullet Holder position and rotation.
cloneBullet =(GameObject) Instantiate (bulletPrefab,transform.position,transform.rotation);
 In order to move the bullet, we added a physics component of rigidbody.  Rigidbody in this example enables us to move game object. According to the research I made, the speed of a bullet is approximately 120m/s to about 320m/s. We already know that the unity engine uses frame per second to execute program. Therefore, we will multiply the forward speed by 120f before finally we make the clone bullet destroy for 2 seconds.  
rb.velocity = transform.forward * 120f;
                        Destroy (cloneBullet, 2f);

Those infinite sphere bullet instantiating from the gun are the clone. The prefab is just one but with the help of the Instantiate() method and a little tweaking, we can create clone bullet of the same type, shape, size, etc. I hope this really help you. See you in the next tutorial.  

No comments:

Post a Comment