Firing the Projectile

From STEAMwiki
Jump to: navigation, search

Add your launcher 3D object (gun / wand / etc) as a child of your FirstPersonCharacter. Add another child object (Create Empty Child) to the tip of the launcher and name it "BarrelEnd". This will indicate to the code where the projectile will spawn. Change the rotation so that the blue arrow (y-axis) points in the direction you want your projectile to launch. Make sure that its position is past the end of your launcher. If your projectile spawns inside of your launcher, it will collide with instantly, making it drop to the ground instead of shooting outwards.

BarrelEnd.png

Set up your projectile prefab. Make sure that it has a collider and a rigidbody component added to it. If you have imported a complex object, add a simple collider to it such as a sphere. You can add particle systems to the prefab if you want them on your projectile.

ProjectilePrefab.png

Next, add a C# script to your launcher and name it "Shoot". Code for this script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Shoot : MonoBehaviour {

    public Rigidbody shotPrefab;
    public Transform barrelEnd;

    // Use this for initialization
    void Start () {
		
    }
	
    // Update is called once per frame
    void Update () {
        if (Input.GetButtonDown("Fire1"))
        {
            Rigidbody shotInstance;
            shotInstance = Instantiate(shotPrefab, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
            shotInstance.AddForce(barrelEnd.forward * 500);
        }
    }
}

Change the velocity 500 to a higher number if you want a faster projectile.

Once the script is added, specify the object references needed for Shot Prefab and Barrel End:

ShootReferences.png

Try it out!

Next, we want the shot to interact with targets. Add the tag "Enemy" to anything you want the shots to hit. We also want the shot to disappear after 1.5 seconds if they haven't hit anything. Add a new script to the prefab and call it "ShotDestroy".

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShotDestroy : MonoBehaviour {

    // Use this for initialization
    void Start () {
        Destroy(gameObject, 1.5f);
    }
	
    // Update is called once per frame
    void Update () {
		
    }

    void OnCollisionEnter(Collision col)
    {
        if (col.gameObject.tag == "Enemy")
        {
            Destroy(col.gameObject);
            Destroy(gameObject, 0.1f);
        }
    }
}



Watch this video for step by step and more information: https://unity3d.com/learn/tutorials/topics/scripting/instantiate