-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExplodingBarrel.cs
More file actions
78 lines (59 loc) · 2.14 KB
/
ExplodingBarrel.cs
File metadata and controls
78 lines (59 loc) · 2.14 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ExplodingBarrel : Pullable
{
[Header("Class Variables")]
[SerializeField]private Vector2 explosionForce;
[SerializeField]private float explosionRadius = 5f;
public bool currentlyExploding = false;
public LayerMask LayerMask;
[SerializeField]private float explosionDelay = 0.5f;
[SerializeField] private GameObject fireParticles;
[SerializeField] private GameObject explosionParticles;
public void OnTriggerEnter(Collider other)
{
if(thrown)
Explode();
}
public override void SpecialInteraction()
{
StartCoroutine(StartTimer());
}
IEnumerator StartTimer()
{
fireParticles.SetActive(true);
yield return new WaitForSeconds(explosionDelay);
Explode();
}
private void Explode()
{
currentlyExploding = true;
Instantiate(explosionParticles, transform.position, Quaternion.identity);
CinemachineShake.instance.ShakeCamera(6,.5f);
const int maxColliders = 50;
var hitColliders = new Collider[maxColliders];
//No garbage allocation and it's faster
var numColliders = Physics.OverlapSphereNonAlloc(transform.position, explosionRadius, hitColliders, LayerMask);
for (var i = 0; i < numColliders; i++)
{
var explosionAmount = UnityEngine.Random.Range(explosionForce.x, explosionForce.y);
var obj = hitColliders[i].gameObject;
//Call the special interaction method on the object
if(obj.TryGetComponent(out Pullable pullable))
pullable.SpecialInteraction();
var rb = obj.GetComponent<Rigidbody>();
if (!rb) return;
rb.AddForce(obj.transform.position - transform.position * (explosionAmount * Time.deltaTime),
ForceMode.Impulse);
}
Destroy(gameObject);
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, explosionRadius);
}
}