GunShoot.cs
2.62 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
using UnityEngine;
using System.Collections;
using Random = UnityEngine.Random;
public class GunShoot : MonoBehaviour {
public float fireRate = 0.25f; // Number in seconds which controls how often the player can fire
public float weaponRange = 20f; // Distance in Unity units over which the player can fire
public Transform gunEnd;
public ParticleSystem muzzleFlash;
public ParticleSystem cartridgeEjection;
public GameObject metalHitEffect;
public GameObject sandHitEffect;
public GameObject stoneHitEffect;
public GameObject waterLeakEffect;
public GameObject waterLeakExtinguishEffect;
public GameObject[] fleshHitEffects;
public GameObject woodHitEffect;
private float nextFire; // Float to store the time the player will be allowed to fire again, after firing
private Animator anim;
private GunAim gunAim;
void Start ()
{
anim = GetComponent<Animator> ();
gunAim = GetComponentInParent<GunAim>();
}
void Update ()
{
if (Input.GetButtonDown("Fire1") && Time.time > nextFire && !gunAim.GetIsOutOfBounds())
{
nextFire = Time.time + fireRate;
muzzleFlash.Play();
cartridgeEjection.Play();
anim.SetTrigger ("Fire");
Vector3 rayOrigin = gunEnd.position;
RaycastHit hit;
if (Physics.Raycast(rayOrigin, gunEnd.forward, out hit, weaponRange))
{
HandleHit(hit);
}
}
}
void HandleHit(RaycastHit hit)
{
if(hit.collider.sharedMaterial != null)
{
string materialName = hit.collider.sharedMaterial.name;
switch(materialName)
{
case "Metal":
SpawnDecal(hit, metalHitEffect);
break;
case "Sand":
SpawnDecal(hit, sandHitEffect);
break;
case "Stone":
SpawnDecal(hit, stoneHitEffect);
break;
case "WaterFilled":
SpawnDecal(hit, waterLeakEffect);
SpawnDecal(hit, metalHitEffect);
break;
case "Wood":
SpawnDecal(hit, woodHitEffect);
break;
case "Meat":
SpawnDecal(hit, fleshHitEffects[Random.Range(0, fleshHitEffects.Length)]);
break;
case "Character":
SpawnDecal(hit, fleshHitEffects[Random.Range(0, fleshHitEffects.Length)]);
break;
case "WaterFilledExtinguish":
SpawnDecal(hit, waterLeakExtinguishEffect);
SpawnDecal(hit, metalHitEffect);
break;
}
}
}
void SpawnDecal(RaycastHit hit, GameObject prefab)
{
GameObject spawnedDecal = GameObject.Instantiate(prefab, hit.point, Quaternion.LookRotation(hit.normal));
spawnedDecal.transform.SetParent(hit.collider.transform);
}
}