SingleWaveLineRenderer.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. [RequireComponent(typeof(LineRenderer))]
  5. public class SingleWaveLineRenderer : MonoBehaviour
  6. {
  7. public LineRenderer lineRenderer;
  8. public int pointCount = 100;
  9. public float lineLength = 6f;
  10. public float amplitude = 0.5f;
  11. public float wavelength = 2f;
  12. public float waveSpeed = 2f;
  13. public float phaseOffset = 0f;
  14. public Transform startPointTransform; // ✅ 控制起点位置和方向的锚点
  15. private float frequency;
  16. void Start()
  17. {
  18. frequency = 2 * Mathf.PI / wavelength;
  19. lineRenderer.positionCount = pointCount;
  20. if (lineRenderer.material != null)
  21. lineRenderer.material.color = Color.cyan;
  22. }
  23. void Update()
  24. {
  25. float step = lineLength / (pointCount - 1);
  26. float time = Time.time;
  27. Vector3 startPos = startPointTransform.position;
  28. Vector3 direction = startPointTransform.right; // ✅ 方向:起点 Transform 的右方向
  29. for (int j = 0; j < pointCount; j++)
  30. {
  31. float x = j * step;
  32. float y = amplitude * Mathf.Sin(frequency * x - waveSpeed * time + phaseOffset);
  33. // ✅ 构建偏移:方向 + 垂直扰动(up 方向)
  34. Vector3 offset = direction.normalized * x + startPointTransform.up * y;
  35. lineRenderer.SetPosition(j, startPos + offset);
  36. }
  37. }
  38. }