Its about adding features in my game development

How can I add a shooting mechanic to my 2D game?

1 Like

Hello Danial.

Please what is the nature of your 2d game. do you have a screenshot or something ?

Hello. Please see image
1.) is my projectile and 2.) is my player
Thanks

attach this script to player. I use a code like this. you need to attach an object to your player called “GunNozzle”. other private fields are used to regulate your fire rates. _LaserPrefab should hold your lazer or players projectile on your scene. This would shoot whenever you hit space or mouse button zero.

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

public class Player : MonoBehaviour
{
    [SerializeField]
    private GameObject _LaserPrefab;
    [SerializeField]
    private float _FireRate = 0.25f;

    private float _CanFire = 0.0f;
    private GameObject _gunNozzle;

    void Start()
    {
        _gunNozzle = GameObject.Find("GunNozzle");
    }

    void Update()
    {
        Shoot();
    }

    private void Shoot()
    {
        if (Input.GetKeyDown(KeyCode.Space) || Input.GetMouseButton(0))
        {
            if (Time.time > _CanFire)
            {
                Vector3 laserSpawnPosition = _gunNozzle.transform.position;

                GameObject laser = Instantiate(_LaserPrefab, laserSpawnPosition, Quaternion.identity);

                _CanFire = Time.time + _FireRate;
            }
        }
    }
}

Thank you