Projectile.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Collections.Generic;
  2. using UnityEngine;
  3. namespace Assets.HeroEditor4D.Common.Scripts.ExampleScripts
  4. {
  5. /// <summary>
  6. /// General behaviour for projectiles: bullets, rockets and other.
  7. /// </summary>
  8. public class Projectile : MonoBehaviour
  9. {
  10. public List<Renderer> Renderers;
  11. public GameObject Trail;
  12. public GameObject Impact;
  13. public Rigidbody Rigidbody;
  14. public void Start()
  15. {
  16. Destroy(gameObject, 5);
  17. }
  18. public void Update()
  19. {
  20. if (Rigidbody != null && Rigidbody.useGravity)
  21. {
  22. transform.right = Rigidbody.velocity.normalized;
  23. }
  24. }
  25. public void OnTriggerEnter2D(Collider2D other)
  26. {
  27. Bang(other.gameObject);
  28. }
  29. public void OnCollisionEnter2D(Collision2D other)
  30. {
  31. Bang(other.gameObject);
  32. }
  33. private void Bang(GameObject other)
  34. {
  35. ReplaceImpactSound(other);
  36. Impact.SetActive(true);
  37. Destroy(GetComponent<SpriteRenderer>());
  38. Destroy(GetComponent<Rigidbody>());
  39. Destroy(GetComponent<Collider>());
  40. Destroy(gameObject, 1);
  41. foreach (var ps in Trail.GetComponentsInChildren<ParticleSystem>())
  42. {
  43. ps.Stop();
  44. }
  45. foreach (var tr in Trail.GetComponentsInChildren<TrailRenderer>())
  46. {
  47. tr.enabled = false;
  48. }
  49. }
  50. private void ReplaceImpactSound(GameObject other)
  51. {
  52. var sound = other.GetComponent<AudioSource>();
  53. if (sound != null && sound.clip != null)
  54. {
  55. Impact.GetComponent<AudioSource>().clip = sound.clip;
  56. }
  57. }
  58. }
  59. }