i3e-asg2/Assets/Scripts/enemyGun.cs

117 lines
2.6 KiB
C#
Raw Normal View History

/*
*Author: Lin Hengrui Ryan
*Date:21/06/2024
*Description: to make a gun script for the enemy
*/
2024-07-02 02:42:09 +00:00
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class enemyGun : MonoBehaviour
{
public GameObject bullet;
[Header("gun stats")]
2024-07-02 02:42:09 +00:00
/// <summary>
///
2024-07-02 02:42:09 +00:00
/// </summary>
public int magSize;
public int damage;
public float timeBtwShots;
public float range;
public float reloadTime;
public int bulletsPerFire;
public bool automaticFire;
/// <summary>
/// gun status
/// </summary>
private bool reloading;
private bool shooting;
private bool readyToShot;
private int bulletsLeft;
[Header("Refrencing")]
2024-07-02 02:42:09 +00:00
/// <summary>
///
2024-07-02 02:42:09 +00:00
/// </summary>
[SerializeField]
Transform fpsCam;
public Transform bulletSpawn;
public bool allowInvoke = true;
[SerializeField]
private GameObject mag;
2024-07-04 17:22:55 +00:00
public AudioSource source;
2024-07-02 02:42:09 +00:00
void Awake()
{
bulletsLeft = magSize;
readyToShot = true;
}
public void Shoot()
{
if (readyToShot && !reloading && bulletsLeft > 0)
{
Debug.Log("Bang");
2024-07-04 17:22:55 +00:00
readyToShot = false;
source.PlayOneShot(GameManager.instance.bang);
2024-07-02 02:42:09 +00:00
GameObject currentBullet = Instantiate(
bullet,
bulletSpawn.position,
Quaternion.identity
);
2024-07-04 17:22:55 +00:00
currentBullet.GetComponent<BulletCollider>().damage = damage;
2024-07-02 02:42:09 +00:00
currentBullet
.GetComponent<Rigidbody>()
.AddForce(transform.forward * range, ForceMode.Impulse);
bulletsLeft--;
if (allowInvoke)
{
Invoke("ResetShot", timeBtwShots);
allowInvoke = false;
}
}
}
void Update()
{
2024-07-04 17:22:55 +00:00
if (bulletsLeft == 0)
2024-07-02 02:42:09 +00:00
{
Reload();
}
}
2024-07-04 17:22:55 +00:00
2024-07-02 02:42:09 +00:00
private void ResetShot()
{
//Allow shooting and invoking again
readyToShot = true;
allowInvoke = true;
}
public void Reload()
{
if (bulletsLeft < magSize && !reloading)
{
2024-07-04 17:22:55 +00:00
source.PlayOneShot(GameManager.instance.reload1);
2024-07-02 02:42:09 +00:00
Debug.Log("reload");
reloading = true;
readyToShot = false;
Invoke("Reloaded", reloadTime);
mag.SetActive(false);
}
}
void Reloaded()
{
2024-07-04 17:22:55 +00:00
source.PlayOneShot(GameManager.instance.reload2);
2024-07-02 02:42:09 +00:00
reloading = false;
readyToShot = true;
bulletsLeft = magSize;
mag.SetActive(true);
}
}