AnimatedSpriteSheet.shader 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. Shader "Funly/Sky Studio/Utility/Animated Sprite Sheet"
  2. {
  3. Properties
  4. {
  5. [NoScaleOffset] _MainTex ("Sprite Texture", 2D) = "white" {}
  6. _SpriteColumnCount ("Sprite Columns", int) = 1
  7. _SpriteRowCount ("Sprite Rows", int) = 1
  8. _SpriteItemCount ("Sprite Total Items", int) = 1
  9. _AnimationSpeed ("Animation Speed", int) = 25
  10. _Intensity ("Intensity", Range(0, 1)) = .7
  11. }
  12. SubShader
  13. {
  14. Tags{ "RenderType" = "Transparent" "Queue" = "Transparent" }
  15. LOD 100
  16. Blend OneMinusDstColor One
  17. Cull Off
  18. Pass
  19. {
  20. CGPROGRAM
  21. #pragma target 2.0
  22. #pragma vertex vert
  23. #pragma fragment frag
  24. #include "UnityCG.cginc"
  25. struct appdata
  26. {
  27. float4 vertex : POSITION;
  28. float2 uv : TEXCOORD0;
  29. };
  30. struct v2f
  31. {
  32. float2 uv : TEXCOORD0;
  33. float4 vertex : SV_POSITION;
  34. };
  35. sampler2D _MainTex;
  36. int _SpriteColumnCount;
  37. int _SpriteRowCount;
  38. int _SpriteItemCount;
  39. int _AnimationSpeed;
  40. float _Intensity;
  41. int GetSpriteTargetIndex(int itemCount, int animationSpeed, float seed) {
  42. float spriteProgress = frac((_Time.y + (10.0f * seed)) / ((float)itemCount / (float)animationSpeed));
  43. return (int)(itemCount * spriteProgress);
  44. }
  45. float2 GetSpriteItemSize(float2 dimensions) {
  46. return float2(1.0f / dimensions.x, (1.0f / dimensions.x) * (dimensions.x / dimensions.y));
  47. }
  48. float2 GetSpriteSheetCoords(float2 uv, float2 dimensions, int targetFrameIndex, float2 itemSize, int numItems) {
  49. int rows = dimensions.y;
  50. int columns = dimensions.x;
  51. float2 scaledUV = float2(uv.x * itemSize.x, uv.y * itemSize.y);
  52. float2 offset = float2(
  53. targetFrameIndex % abs(columns) * itemSize.x,
  54. ((rows - 1) - (targetFrameIndex / abs(columns))) * itemSize.y);
  55. return scaledUV + offset;
  56. }
  57. float2 GetAnimatedSpriteCoords(float2 uv) {
  58. float2 dimensions = float2(_SpriteColumnCount, _SpriteRowCount);
  59. float2 itemSize = GetSpriteItemSize(dimensions);
  60. int spriteIndex = GetSpriteTargetIndex(_SpriteItemCount, _AnimationSpeed, 1.0f);
  61. return GetSpriteSheetCoords(uv, dimensions, spriteIndex, itemSize, _SpriteItemCount);
  62. }
  63. v2f vert (appdata v)
  64. {
  65. v2f o;
  66. o.vertex = UnityObjectToClipPos(v.vertex);
  67. o.uv = saturate(GetAnimatedSpriteCoords(v.uv));
  68. return o;
  69. }
  70. fixed4 frag (v2f i) : SV_Target
  71. {
  72. return tex2D(_MainTex, i.uv) * _Intensity;
  73. }
  74. ENDCG
  75. }
  76. }
  77. }