-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShooting.cs
63 lines (54 loc) · 1.47 KB
/
Shooting.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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooting : MonoBehaviour
{
public Transform firePoint;
[SerializeField] float cooldown = 1F;
[SerializeField] int bulletForce = 180;
[SerializeField] float reloadTime = 2;
public int ammo = 6;
public AudioSource reloadingSound;
bool reloading = false;
float timeStamp = 0.0F;
private void Start()
{
reloadingSound = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetButton("Fire1") && CanFire())
{
Shoot();
timeStamp = Time.time + cooldown;
}
if (Input.GetKeyDown("r") && !reloading)
{
StartCoroutine(Reload());
}
}
void Shoot()
{
Vector2 origin = firePoint.transform.position;
Vector2 direction = firePoint.transform.right;
RaycastHit2D hit = Physics2D.Raycast(origin, direction, 100f, LayerMask.GetMask("Enemy"));
if (hit.collider != null)
{
hit.rigidbody.AddForceAtPosition(direction * bulletForce, hit.point);
hit.collider.GetComponent<Enemy>().Damage();
}
ammo--;
}
IEnumerator Reload()
{
reloading = true;
reloadingSound.Play();
yield return new WaitForSeconds(reloadTime);
reloading = false;
ammo = 6;
}
bool CanFire()
{
return (timeStamp <= Time.time && ammo > 0 && !reloading);
}
}