I am making a game where the character just has to shoot enemies to move on, but I wanted to add variety to my game and add more guns, like a shotgun. Problem being no matter what I try, either it doesn’t hit the enemy, or the bullet spawn, but don’t move. I am very new to Unity, so a clear explanation, or example would be greatly appreciated
Here is the codes:
For my regular Pistol (which works):
[RequireComponent(typeof(AudioSource))]
public class Weapon : MonoBehaviour
{
public Transform firePoint;
public GameObject bulletPrefab;
public AudioClip firingSound;
public int ammo = 10;
public bool isFiring;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1") && ammo > 0)
{
Shoot();
}
if (Input.GetKey(KeyCode.R))
{
ammo = 10;
}
}
public void Shoot()
{
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
AudioSource.PlayClipAtPoint(firingSound, new Vector3(0, 0, 0));
isFiring = true;
ammo--;
isFiring = false;
}
}
For my bullet:
public float speed = 10f;
public int damage = 34;
public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb.velocity = transform.right * speed;
}
void OnTriggerEnter2D(Collider2D hitInfo)
{
EnemyHealth enemy = hitInfo.GetComponent<EnemyHealth>();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
Destroy(gameObject);
}
void OnBecameInvisible()
{
enabled = false;
Destroy(gameObject);
}
For my shotgun, I though all I have to do is add 2 more firePoints, then angle them slightly, make the bullet Instantiate there, and boom, easy as that, but no, it has caused me 10 hours of searching for different methods:
public Transform firePoint, firePoint1, firePoint2;
public GameObject bulletPrefab;
public AudioClip firingSound;
public int ammo = 10;
public bool isFiring;
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Fire1") && ammo > 0)
{
Shoot();
}
if (Input.GetKey(KeyCode.R))
{
ammo = 10;
}
}
public void Shoot()
{
Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
Instantiate(bulletPrefab, firePoint1.position, firePoint1.rotation);
Instantiate(bulletPrefab, firePoint2.position, firePoint2.rotation);
AudioSource.PlayClipAtPoint(firingSound, new Vector3(0, 0, 0));
isFiring = true;
ammo--;
isFiring = false;
}
}
Oh and my code for the gun looking at my character if you need:
public float speed = 10f;
public GameObject player;
void Update()
{
// Rotate the object around its local X axis at 1 degree per second
transform.Rotate(Vector3.forward * speed * Time.deltaTime);
}
void LateUpdate()
{
this.transform.position = new Vector3(player.transform.position.x, player.transform.position.y, 0);
Vector2 dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
Thanks in advance