UVAnimCtrl.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using UnityEngine;
  2. using System.Collections;
  3. public class UVAnimCtrl : MonoBehaviour
  4. {
  5. public bool loop=true;
  6. public float scrollSpeed = 5;
  7. public float countX = 4;
  8. public float countY = 4;
  9. private float offsetX = 0.0f;
  10. private float offsetY = 0.0f;
  11. private Vector2 singleTextureSize;
  12. private float _frame = 0.0f;
  13. private float stepx;
  14. private float stepy;
  15. public bool isOffset = false;
  16. public float ox = 0.0f;
  17. public float oy = 0.0f;
  18. private bool _isEnable = true;
  19. public bool isEnable
  20. {
  21. get { return _isEnable; }
  22. set {
  23. _isEnable = value;
  24. if (value) enabled = true;
  25. }
  26. }
  27. void Awake()
  28. {
  29. singleTextureSize = new Vector2(1.0f / countX, 1.0f / countY);
  30. GetComponent<Renderer>().material.mainTextureScale = singleTextureSize;
  31. foreach (Material i in GetComponent<Renderer>().materials)
  32. {
  33. i.mainTextureScale = singleTextureSize;
  34. }
  35. }
  36. /// <summary>
  37. /// Update用于普通更新的情况,与enable和isEnable搭配使用;与UpdateFrame互斥
  38. /// </summary>
  39. void Update()
  40. {
  41. if (_isEnable) _OnUpdate();
  42. else this.enabled = false;
  43. }
  44. public void UpdateFrame()
  45. {
  46. _OnUpdate();
  47. }
  48. private void _OnUpdate()
  49. {
  50. if(isOffset)
  51. {
  52. if(loop)
  53. {
  54. if(offsetX <-1) offsetX +=1;
  55. if(offsetY < -1) offsetY +=1;
  56. if(offsetX >1) offsetX -=1;
  57. if(offsetY >1) offsetY -=1;
  58. }
  59. else
  60. {
  61. if(offsetX <-1) return;
  62. if(offsetY < -1) return;
  63. if(offsetX >1) return;
  64. if(offsetY >1) return;
  65. }
  66. offsetX += ox;
  67. offsetY += oy;
  68. }
  69. else
  70. {
  71. if (stepy >=countY){
  72. if(loop){
  73. stepy = 0f;
  74. }
  75. else
  76. {
  77. return;
  78. }
  79. }
  80. _frame += Time.deltaTime;
  81. stepx = Mathf.Floor(_frame * scrollSpeed);
  82. offsetX = stepx / countX;
  83. if (stepx >= countX)
  84. {
  85. stepy+=1;
  86. _frame = 0;
  87. }
  88. offsetY = stepy / countY;
  89. //offsetY = -(_frame - _frame % countX) / countY / countX;
  90. }
  91. foreach (Material i in GetComponent<Renderer>().materials)
  92. {
  93. i.SetTextureOffset("_MainTex", new Vector2(offsetX, offsetY));
  94. }
  95. }
  96. }