Hi, i have this code and i want to add more bullets with a variable so i can change the amount of bullets per shot in game, also i want to create a random spread. How can i do it?
Thanks
using UnityEngine;
public class ProjectileShooting : MonoBehaviour
{
public GameObject bulletPrefab;
public Transform firePoint;
public float bulletForce = 20f;
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody rb = bullet.GetComponent<Rigidbody>();
rb.AddForce(firePoint.forward * bulletForce, ForceMode.Impulse);
}
}
Hello, here is a simple code for what you want to achieve. I haven’t tested the code but it should work fine. You may want to change the direction of spread of the bullets. With each button click the for loop instantiates x bullets (bulletsPerShot). Then the “spread” gets added to the moving direction. Hope this helps!
using UnityEngine;
public class ProjectileShooting : MonoBehaviour
{
public GameObject bulletPrefab;
public Transform firePoint;
public float bulletForce = 20f;
public int bulletsPerShot = 1; // Variable to set the number of bullets per shot
public float spreadAngle = 5f; // Angle for random spread
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
for (int i = 0; i < bulletsPerShot; i++)
{
Vector3 spread = new Vector3(
Random.Range(-spreadAngle, spreadAngle),
Random.Range(-spreadAngle, spreadAngle),
0
);
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Rigidbody rb = bullet.GetComponent<Rigidbody>();
Quaternion spreadRotation = Quaternion.Euler(spread);
Vector3 directionWithSpread = spreadRotation * firePoint.forward;
rb.AddForce(directionWithSpread * bulletForce, ForceMode.Impulse);
}
}
}