okay so I am working on a 2D shooting game and I made a script which makes the gun aimed at the direction of the mouse cursor, and I have succeeded into making a pistol and an assault rifle but I don’t really know how to make a shotgun and I don’t know how to make the bullets spread randomly in the direction of the mouse cursor
| here is the code of the basic pistol
public class Pistol : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public GameObject reloadingText;
public int maxAmmo = 10;
private int currentAmmo;
public float reloadTime = 1f;
private bool isReloading = false;
void Start()
{
currentAmmo = maxAmmo;
}
void Update()
{
if (isReloading)
return;
if (currentAmmo <= 0)
{
StartCoroutine(Reload());
return;
}
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
IEnumerator Reload()
{
isReloading = true;
reloadingText.SetActive(true);
yield return new WaitForSeconds(reloadTime);
reloadingText.SetActive(false);
currentAmmo = maxAmmo;
isReloading = false;
}
void Shoot()
{
currentAmmo--;
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
}
}
and here is the code of the bullet
public class Bullet : MonoBehaviour
{
public float speed = 20f;
public Rigidbody2D rb;
public GameObject bulletCollisionEffect;
public int damage = 40;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.right * speed;
}
void OnTriggerEnter2D (Collider2D hitInfo)
{
Enemy enemy = hitInfo.GetComponent<Enemy>();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
Destroy(gameObject);
Instantiate(bulletCollisionEffect, transform.position, Quaternion.identity);
}
}
help would be really appreciated.
edit: I forgot to put the code where I make the gun aim at the mouse cursor :
public class Pivot : MonoBehaviour
{
public GameObject myPlayer;
// Update is called once per frame
private void FixedUpdate()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
difference.Normalize();
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotationZ);
if (rotationZ < -90 || rotationZ > 90)
{
if (myPlayer.transform.eulerAngles.y == 0)
{
transform.localRotation = Quaternion.Euler(180, 0, -rotationZ);
} else if (myPlayer.transform.eulerAngles.y == 180) {
transform.localRotation = Quaternion.Euler(180, 180, -rotationZ);
}
}
}
}