Sunday, October 21, 2018

Physics based aircraft 2 / 2 - Gun

Lets arm our aircraft from previous tutorial with a simple gun. We will need two scripts (one for a gun and one for a projectile), and also a prefab for projectile itself. For projectile, we'll use Particle System. It's very useful and powerful component, you can read about it here if you are curious. But for now, just create one and set it up according to these screenshots: Next, we should create a script for our projectile, lets call it Projectile.cs
using UnityEngine;
 
public class Projectile : MonoBehaviour
{
    // Reference to our Rigidbody to use later
    private Rigidbody rb;
 
    // Reference to our ParticleSystem to use later
    private ParticleSystem ps;
 
    // Use this for initialization
    void Start()
    {
        // Find our Rigidbody
        rb = GetComponent<Rigidbody>();
 
        // Find our ParticleSystem
        ps = GetComponent<ParticleSystem>();
 
        // Make sure our projectile disappears eventually
        // even if dont hit anything
        Invoke("Die", 5);
    }
 
    // Destroy nicely our projectile
    void Die()
    {
        // Stop emiting particles
        ps.Stop();
 
        // Disable collisions
        rb.detectCollisions = false;
 
        // Actually destroy after 2 seconds (to let particle emitter finish)
        Destroy(gameObject, 2);
    }
 
    // What should happen if we collide with something
    private void OnCollisionEnter(Collision collision)
    {
        // Disable inheriting velocity
        var iv = ps.inheritVelocity;
        iv.enabled = false;
 
        // Emit some particles to simulate impact
        for (int i = 0; i < 20; i++)
        {
            ps.Emit(new ParticleSystem.EmitParams()
            { velocity = collision.contacts[0].normal + Random.onUnitSphere * 2 }, 1);
        }
 
        // Destroy our projectile
        Die();
    }
}
Now we can add Rigidbody, Sphere Collider and our new Projectile script. Set them up according to next screenshot, and create prefab out of our Projectile by dragging it from the Hierarchy window on the left to the Assets window on the bottom (you can delete projectile from the scene afterwards). It's time to make a gun. Create new script, Gun.cs:
using UnityEngine;
 
public class Gun : MonoBehaviour
{
    //Our projectile prefab
    public Rigidbody projectilePrefab;
 
    //How fast projectiles will go
    public float initialVelocity = 100.0f;
 
    // How often our gun can fire
    public float fireDelay = 0.25f;
 
    // How much time since last shoot
    private float t = 0;
 
    // Reference to our Rigidbody to use later
    private Rigidbody rb;
 
    // Use this for initialization
    void Start()
    {
        // Find our Rigidbody
        rb = GetComponentInParent<Rigidbody>();
    }
 
    // Update is called once per frame
    void Update()
    {
        // Increase our shoot timer
        t += Time.deltaTime;
 
        // If it isn't too early and we are pressing Fire1 button (left CTRL by default)
        if (t > fireDelay && Input.GetButton("Fire1"))
        {
            // Reset shoot timer
            t = 0;
 
            // Instantiate our projectile and send it flying
            var pr = Instantiate(projectilePrefab, transform.position, transform.rotation);
            pr.velocity = transform.forward * initialVelocity;
 
            // If we have a rigidbody, projectile should inherit it's velocity
            if (rb != null)
            {
                pr.velocity += rb.velocity;
            }
        }
    }
}
Lets install our new gun into our ship. Create empty GameObject as a child of our ship, rename it to Gun and position it in front of the ship. Make sure it's quite far from the ship's own collider, or else you might fly right into the projectile you just launched and kill yourself... It will launch projectiles in the direction of blue arrow, so make sure it's rotated correctly too.

When you are done, add Gun.cs script to our new GameObject and drag Projectile prefab into 'Projectile Prefab' field of our gun: Congratulations, now your ship is armed! Feel free to experiment with adding multiple guns, changing rate of fire or improving visuals of projectiles.

No comments:

Post a Comment