/
Weapon.cs
80 lines (71 loc) · 1.94 KB
/
Weapon.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class Weapon : MonoBehaviour
{
[SerializeField] Camera FPCamera;
[SerializeField] float range = 100f;
[SerializeField] float damage = 30f;
[SerializeField] ParticleSystem muzzleFlash;
[SerializeField] GameObject hitEffect;
[SerializeField] Ammo ammoSlot;
[SerializeField] AmmoType ammoType;
[SerializeField] float timeBetweenShots = 0.5f;
[SerializeField] TextMeshProUGUI ammoText;
bool canShoot = true;
private void OnEnable()
{
canShoot = true;
}
void Update()
{
DisplayAmmo();
if (Input.GetMouseButtonDown(0) && canShoot == true)
{
StartCoroutine(Shoot());
}
}
private void DisplayAmmo()
{
int currentAmmo = ammoSlot.GetCurrentAmmo(ammoType);
ammoText.text = currentAmmo.ToString();
}
IEnumerator Shoot()
{
canShoot = false;
if (ammoSlot.GetCurrentAmmo(ammoType) > 0)
{
PlayMuzzleFlash();
ProcessRaycast();
ammoSlot.ReduceCurrentAmmo(ammoType);
}
yield return new WaitForSeconds(timeBetweenShots);
canShoot = true;
}
private void PlayMuzzleFlash()
{
muzzleFlash.Play();
}
private void ProcessRaycast()
{
RaycastHit hit;
if (Physics.Raycast(FPCamera.transform.position, FPCamera.transform.forward, out hit, range))
{
CreateHitImpact(hit);
EnemyHealth target = hit.transform.GetComponent<EnemyHealth>();
if (target == null) return;
target.TakeDamage(damage);
}
else
{
return;
}
}
private void CreateHitImpact(RaycastHit hit)
{
GameObject impact = Instantiate(hitEffect, hit.point, Quaternion.LookRotation(hit.normal));
Destroy(impact, .1f);
}
}