ElectricLineController.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using UnityEngine;
  2. public class ElectricLineController : MonoBehaviour
  3. {
  4. public Transform pointA;
  5. public Transform pointB;
  6. public Material electricMaterial;
  7. public int columns = 2; // 帧列数
  8. public int rows = 8; // 帧行数
  9. public float frameRate = 0.05f;
  10. private LineRenderer lineRenderer;
  11. private int currentFrame = 0;
  12. private float timer = 0f;
  13. void Start()
  14. {
  15. lineRenderer = GetComponent<LineRenderer>();
  16. lineRenderer.positionCount = 2;
  17. Vector2 scale = new Vector2(1f / columns, 1f / rows);
  18. electricMaterial.SetTextureScale("_MainTex", scale);
  19. /*electricMaterial.SetInt("_ZWrite", 0); // 不写入深度
  20. electricMaterial.SetInt("_ZTest", (int)UnityEngine.Rendering.CompareFunction.Always); // 永远显示
  21. electricMaterial.renderQueue = 5000; // Overlay*/
  22. }
  23. void Update()
  24. {
  25. // 实时更新两点位置
  26. if (pointA && pointB)
  27. {
  28. lineRenderer.SetPosition(0, pointA.position);
  29. lineRenderer.SetPosition(1, pointB.position);
  30. }
  31. // 播放序列帧
  32. timer += Time.deltaTime;
  33. if (timer >= frameRate)
  34. {
  35. timer -= frameRate;
  36. currentFrame = (currentFrame + 1) % (columns * rows);
  37. int col = currentFrame % columns;
  38. int row = currentFrame / columns;
  39. // Y 要倒着来
  40. Vector2 offset = new Vector2((float)col / columns, 1f - ((float)(row + 1) / rows));
  41. electricMaterial.SetTextureOffset("_MainTex", offset);
  42. }
  43. }
  44. }