ArrowCircleMotion.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. public class ArrowCircleMotion : MonoBehaviour
  4. {
  5. public Transform targetPoint; // 圆心
  6. public float radius = 1f; // 半径
  7. public int arrowCount = 5; // 箭头数量
  8. public GameObject arrowPrefab; // 箭头预制体
  9. public float speed = 30f; // 旋转速度(度/秒)
  10. public Vector3 eulerRotation; // 圆的方向(圆的法线朝向)
  11. private List<Transform> arrows = new List<Transform>();
  12. private List<float> angles = new List<float>();
  13. private Quaternion circleRotation;
  14. public float modelForwardOffset = -90f; // 若模型默认朝 Y+
  15. void Start()
  16. {
  17. if (!arrowPrefab || !targetPoint) return;
  18. circleRotation = Quaternion.Euler(eulerRotation);
  19. for (int i = 0; i < arrowCount; i++)
  20. {
  21. GameObject arrow = Instantiate(arrowPrefab, transform);
  22. arrows.Add(arrow.transform);
  23. float angle = (360f / arrowCount) * i;
  24. angles.Add(angle);
  25. }
  26. }
  27. void Update()
  28. {
  29. circleRotation = Quaternion.Euler(eulerRotation);
  30. for (int i = 0; i < arrows.Count; i++)
  31. {
  32. // 更新角度
  33. angles[i] += -speed * Time.deltaTime;
  34. angles[i] %= 360f;
  35. float angle = angles[i];
  36. float selfRotateAngle = angle - 90f; // 自转角度,给Z轴旋转用(修正模型朝向)
  37. // 计算位置
  38. float rad = angle * Mathf.Deg2Rad;
  39. Vector3 localPos = new Vector3(Mathf.Cos(rad) * radius, Mathf.Sin(rad) * radius, 0f);
  40. Vector3 worldPos = targetPoint.position + circleRotation * localPos;
  41. arrows[i].position = worldPos;
  42. // 速度为负时,箭头绕Z轴旋转180度反向
  43. if (speed < 0f)
  44. {
  45. selfRotateAngle = angle + 90f;
  46. Quaternion flipRotation = Quaternion.AngleAxis(selfRotateAngle, Vector3.forward);
  47. arrows[i].rotation = circleRotation * flipRotation;
  48. }
  49. else
  50. {
  51. selfRotateAngle = angle - 90f;
  52. // 计算旋转(公转方向 + 自转修正)
  53. Quaternion zSelfRotation = Quaternion.AngleAxis(selfRotateAngle, Vector3.forward);
  54. arrows[i].rotation = circleRotation * zSelfRotation;
  55. }
  56. }
  57. }
  58. }