Grenade.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using UnityEngine;
  2. public class Grenade : MonoBehaviour
  3. {
  4. public float fuseTime = 3f;
  5. public float explosionRadius = 5f;
  6. public float explosionForce = 700f;
  7. public GameObject explosionEffect;
  8. private float countdown;
  9. private bool hasExploded = false;
  10. void Start()
  11. {
  12. countdown = fuseTime;
  13. }
  14. void Update()
  15. {
  16. countdown -= Time.deltaTime;
  17. if (countdown <= 0f && !hasExploded)
  18. {
  19. Explode();
  20. hasExploded = true;
  21. }
  22. }
  23. void OnCollisionEnter(Collision collision)
  24. {
  25. var target = collision.gameObject.GetComponent<GrenadeTarget>();
  26. if (target != null)
  27. {
  28. if (!hasExploded)
  29. {
  30. Explode();
  31. hasExploded = true;
  32. }
  33. }
  34. }
  35. void Explode()
  36. {
  37. if (explosionEffect)
  38. {
  39. Instantiate(explosionEffect, transform.position, transform.rotation);
  40. }
  41. var collidersToDamage = Physics.OverlapSphere(transform.position, explosionRadius);
  42. foreach (var nearbyObject in collidersToDamage)
  43. {
  44. var target = nearbyObject.GetComponent<GrenadeTarget>();
  45. if (target)
  46. {
  47. target.DestroyTarget();
  48. }
  49. }
  50. var collidersToMove = Physics.OverlapSphere(transform.position, explosionRadius);
  51. foreach (var nearbyObject in collidersToMove)
  52. {
  53. var rb = nearbyObject.GetComponent<Rigidbody>();
  54. if (rb)
  55. {
  56. rb.AddExplosionForce(explosionForce, transform.position, explosionRadius);
  57. }
  58. }
  59. Destroy(gameObject);
  60. }
  61. }