You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.4 KiB

  1. using UnityEngine;
  2. using System.Collections;
  3. public class SparkParticles : MonoBehaviour
  4. {
  5. public Transform BillboardTarget;
  6. ParticleSystem _particleSystem;
  7. // There is a fixed buffer size for particles hacked into this script.
  8. // This means the script will cap the max number of particles to whatever the length of this array is.
  9. // It's ugly I know. Sorry!
  10. ParticleSystem.Particle[] _particles = new ParticleSystem.Particle[25];
  11. void Awake()
  12. {
  13. _particleSystem = GetComponent<ParticleSystem>();
  14. if (BillboardTarget == null)
  15. BillboardTarget = Camera.main.transform;
  16. }
  17. void FixParticleRotations()
  18. {
  19. int count = _particleSystem.GetParticles(_particles);
  20. for (int i = 0; i < count; i++)
  21. {
  22. Vector3 dir = _particles[i].velocity.normalized;
  23. float rot = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
  24. _particles[i].rotation = rot;
  25. }
  26. _particleSystem.SetParticles(_particles, _particleSystem.particleCount);
  27. }
  28. public void Play()
  29. {
  30. transform.LookAt(BillboardTarget);
  31. _particleSystem.Play();
  32. StartCoroutine(LateFix());
  33. }
  34. // It seems setting the rotations on the frame you tell the system to Play is insufficient.
  35. // So this handy coroutine delays that by a single frame.
  36. IEnumerator LateFix()
  37. {
  38. yield return null;
  39. FixParticleRotations();
  40. }
  41. }