Shooting Enemies in UnityHow to Fire Projectiles from an Object

Author Waldo
Published March 1, 2019

In this video I will show you how to shoot projectiles out of a moving object.

Video Walkthrough

  • 0:58 - Importing Bullet from Photoshop
  • 1:20 - Creating a 2D projectile prefab
  • 1:50 - Creating a script to move the projectile towards the enemy
  • 3:40 - Cloning our projectile prefab everytime we press the Space Bar
  • 5:00 - Removing Enemy & Projectile from screen & loading an explosion animation

Source Code for bullet.cs

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

public class bullet : MonoBehaviour {
    public float speed = 50.0f;
    private Rigidbody2D rb;
    private Vector2 screenBounds;

    public GameObject explosion;

    // Use this for initialization
    void Start () {
        rb = this.GetComponent<Rigidbody2D>();
        rb.velocity = new Vector2(speed, 0);
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
    }

    // Update is called once per frame
    void Update () {
        if(transform.position.x > screenBounds.x * -2){
            Destroy(this.gameObject);
        }
    }
    private void OnTriggerEnter2D(Collider2D other){
        if(other.tag == "asteroid"){
            GameObject e = Instantiate(explosion) as GameObject;
            e.transform.position = transform.position;
            Destroy(other.gameObject);
            Destroy(this.gameObject);
        }
    }
}

Source Code for desktopMovement.cs

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

public class desktopMovement : MonoBehaviour {
    public Transform player;
    public float speed = 5.0f;
    public GameObject bulletPrefab;

    // Update is called once per frame
    void Update(){
        moveCharacter(new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical")));
        if(Input.GetKeyDown("space")){
            shootBullet();
        }
    }

    void moveCharacter(Vector2 direction){
        player.Translate(direction * speed * Time.deltaTime);
    }
    public void shootBullet(){
        GameObject b = Instantiate(bulletPrefab) as GameObject;
        b.transform.position = player.transform.position;
    }
}

Resources

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About