JamesMakesGames

Grenade

Feb 24th, 2022
689
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.45 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. [RequireComponent(typeof(Rigidbody))]
  4. public class Grenade : MonoBehaviour, IThrowable, IDamageable
  5. {
  6.     [SerializeField] private float damage;
  7.     [SerializeField] private float speed;
  8.     [SerializeField] private float range;
  9.     [SerializeField] private float timeBeforeDetonation;
  10.  
  11.     [SerializeField] private GameObject explosionEffect;
  12.  
  13.     private float detonationTime = float.MaxValue;
  14.     private bool isExploding;
  15.  
  16.     private void Update()
  17.     {
  18.         if (isExploding) return;
  19.  
  20.         if (Time.time > detonationTime)
  21.         {
  22.             Explode();
  23.         }
  24.     }
  25.  
  26.     public void Throw(Vector3 direction)
  27.     {
  28.         GetComponent<Rigidbody>().AddForce(direction.normalized * speed);
  29.  
  30.         detonationTime = Time.time + timeBeforeDetonation;
  31.     }
  32.  
  33.     public void Damage(float damageAmount)
  34.     {
  35.         Explode();
  36.     }
  37.  
  38.     private void Explode()
  39.     {
  40.         if (isExploding) return;
  41.  
  42.         isExploding = true;
  43.  
  44.         Instantiate(explosionEffect, transform.position, Quaternion.identity);
  45.  
  46.         Collider[] colliders = Physics.OverlapSphere(transform.position, range);
  47.  
  48.         foreach (Collider collider in colliders)
  49.         {
  50.             IDamageable damageable = collider.GetComponent<IDamageable>();
  51.             if (damageable != null)
  52.             {
  53.                 damageable.Damage(damage);
  54.             }
  55.         }        
  56.  
  57.         Destroy(gameObject);
  58.     }
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment