Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- [RequireComponent(typeof(Rigidbody))]
- public class Grenade : MonoBehaviour, IThrowable, IDamageable
- {
- [SerializeField] private float damage;
- [SerializeField] private float speed;
- [SerializeField] private float range;
- [SerializeField] private float timeBeforeDetonation;
- [SerializeField] private GameObject explosionEffect;
- private float detonationTime = float.MaxValue;
- private bool isExploding;
- private void Update()
- {
- if (isExploding) return;
- if (Time.time > detonationTime)
- {
- Explode();
- }
- }
- public void Throw(Vector3 direction)
- {
- GetComponent<Rigidbody>().AddForce(direction.normalized * speed);
- detonationTime = Time.time + timeBeforeDetonation;
- }
- public void Damage(float damageAmount)
- {
- Explode();
- }
- private void Explode()
- {
- if (isExploding) return;
- isExploding = true;
- Instantiate(explosionEffect, transform.position, Quaternion.identity);
- Collider[] colliders = Physics.OverlapSphere(transform.position, range);
- foreach (Collider collider in colliders)
- {
- IDamageable damageable = collider.GetComponent<IDamageable>();
- if (damageable != null)
- {
- damageable.Damage(damage);
- }
- }
- Destroy(gameObject);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment