Dust.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. public class Dust : MonoBehaviour {
  5. public Animator animator;
  6. private float direction;
  7. private float dirSpeed;
  8. private float speed;
  9. private float speedAcc;
  10. private float duration;
  11. private float startTime;
  12. private bool isHiding;
  13. public void Show()
  14. {
  15. gameObject.SetActive(true);
  16. animator.Play("DustShow", 0, 0);
  17. direction = Random.Range(0, 2f*Mathf.PI);
  18. duration = Random.Range(5f, 10f);
  19. startTime = GameTime.time;
  20. isHiding = false;
  21. Rotate();
  22. }
  23. public void Hide()
  24. {
  25. isHiding = true;
  26. animator.Play("DustHide", 0, 0);
  27. }
  28. public void Remove()
  29. {
  30. gameObject.SetActive(false);
  31. if(!cacheList.Contains(this))
  32. cacheList.Add(this);
  33. }
  34. // Update is called once per frame
  35. void Update ()
  36. {
  37. Vector3 pos = transform.position;
  38. pos.x += Mathf.Cos(direction) * speed * GameTime.deltaTime;
  39. pos.z += Mathf.Sin(direction) * speed * GameTime.deltaTime;
  40. transform.position = pos;
  41. direction += dirSpeed*GameTime.deltaTime;
  42. speed += 0.01f*GameTime.deltaTime;
  43. speed = NumberUtil.forceBetween(speed, 0.5f, 3f);
  44. if(Random.Range(0, 100) < 5)
  45. speed += Random.Range(-0.5f, 0.5f);
  46. if(Random.Range(0, 100) < 5)
  47. dirSpeed = Random.Range(-2f, 2f);
  48. Rotate();
  49. if(!isHiding && GameTime.time - startTime > duration)
  50. Hide();
  51. }
  52. private void Rotate()
  53. {
  54. Vector3 angle = transform.eulerAngles;
  55. angle.y = -NumberUtil.radianToAngle(direction);
  56. transform.eulerAngles = angle;
  57. }
  58. private static List<Dust> cacheList = new List<Dust>();
  59. public static Dust CreateDust(GameObject prefab)
  60. {
  61. Dust dust = null;
  62. if(cacheList.Count > 0)
  63. {
  64. dust = cacheList[0];
  65. cacheList.RemoveAt(0);
  66. }
  67. else
  68. {
  69. GameObject obj = Instantiate<GameObject>(prefab);
  70. DontDestroyOnLoad(obj);
  71. dust = obj.GetComponent<Dust>();
  72. }
  73. return dust;
  74. }
  75. }