- Home /
How to make bullets spread in unity2D?
Hello, I'm trying to make a 2d game that contains shotgun, so I don't know how exactly to make the bullets spread. I tried to write a code that may solve my problem but doesn't work.
My code:
public class Shooting : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public Weapon currentWeapon;
private float nextTimeOfFire = 0;
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
if(currentWeapon)
{
if(Time.time >= nextTimeOfFire)
{
for(float x = 0;x < currentWeapon.GetBullets(); x++)
{
Shoot();
}
nextTimeOfFire = Time.time + 1 / currentWeapon.fireRate;
}
}
}
}
void Shoot(){
Instantiate(bulletPrefab,firePoint.position, Quaternion.Euler(firePoint.rotation.x, firePoint.rotation.y + Random.Range(-currentWeapon.GetSpread(), currentWeapon.GetSpread()), 0));
}
}
**Note:**Weapon class is a scriptable object and that's his code:
[CreateAssetMenu(fileName = "New Weapon", menuName = "Weapon")]
public class Weapon : ScriptableObject
{
public Sprite currentWeaponSpr;
public GameObject bulletPrefab;
public float fireRate;
public int damage;
public float bullet;
public float spread = 0;
public float GetFireRate(){
return fireRate;
}
public int GetDamage(){
return damage;
}
public float GetBullets(){
return bullet;
}
public float GetSpread(){
return spread;
}
}
if anyone can help me please give me your hand.
Comment
Your answer
Follow this Question
Related Questions
Shotgun raycast 1 Answer
my prefab is null woe 2 Answers
2D Character Shooting 0 Answers
Multiple Bullets 2 Answers
fps shooting enemy 1 Answer