MultipleCrossHair.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. //多准心渲染姿态角-测试用
  6. public class MultipleCrossHair : MonoBehaviour
  7. {
  8. List<RectTransform> crossHairList = new List<RectTransform>();
  9. void Start()
  10. {
  11. BowCamera.ins.onAfterLateUpdate += MyUpdate;
  12. crossHairList.Add(CreateNewCrossHair(Color.green));
  13. crossHairList.Add(CreateNewCrossHair(Color.yellow));
  14. }
  15. readonly Vector3 centerPoint = new Vector3(0.5f, 0.5f, 0);
  16. void MyUpdate()
  17. {
  18. UpdateCrossHairByRotation(crossHairList[0], Quaternion.identity);
  19. UpdateCrossHairByRotation(crossHairList[0], Quaternion.identity);
  20. }
  21. public void UpdateCrossHairByRotation(RectTransform rectTF, Quaternion rotation)
  22. {
  23. Vector3 theAngles = rotation.eulerAngles;
  24. float bowRotateConvertRate = UserSettings.ins.bowRotateConvert.GetRate();
  25. theAngles.x = Mathf.Clamp((theAngles.x > 180 ? theAngles.x - 360 : theAngles.x) * bowRotateConvertRate,
  26. -80, 80);
  27. theAngles.y = Mathf.Clamp((theAngles.y > 180 ? theAngles.y - 360 : theAngles.y) * bowRotateConvertRate,
  28. -80, 80);
  29. Transform TF = BowCamera.ins.transform;
  30. Vector3 forward = GameMgr.ins.transform.rotation * (Quaternion.Euler(theAngles) * Vector3.forward);
  31. Ray ray = new Ray(TF.position, forward);
  32. RaycastHit hitInfo;
  33. Vector3 targetPosition;
  34. if (Physics.Raycast(ray, out hitInfo, 100))
  35. {
  36. targetPosition = hitInfo.point;
  37. }
  38. else
  39. {
  40. targetPosition = TF.position + forward * 100f;
  41. }
  42. RectTransform parentRTF = CrossHair.ins.transform.parent.GetComponent<RectTransform>();
  43. Vector3 v3 = Camera.main.WorldToViewportPoint(targetPosition) - centerPoint;
  44. v3.x *= parentRTF.rect.width;
  45. v3.y *= parentRTF.rect.height;
  46. v3.z = 0;
  47. rectTF.localPosition = v3;
  48. }
  49. //创建一个新的准心
  50. RectTransform CreateNewCrossHair(Color color)
  51. {
  52. Transform parentTF = CrossHair.ins.transform.parent;
  53. RectTransform RTF = new GameObject().AddComponent<RectTransform>();
  54. RTF.SetParent(parentTF);
  55. RTF.localRotation = Quaternion.identity;
  56. RTF.localPosition = Vector3.zero;
  57. RTF.localScale = new Vector3(1, 1, 1);
  58. RTF.gameObject.AddComponent<CanvasRenderer>().cullTransparentMesh = false;
  59. Image imgComp = RTF.gameObject.AddComponent<Image>();
  60. imgComp.sprite = CrossHair.ins.GetComponent<Image>().sprite;
  61. imgComp.SetNativeSize();
  62. Material mat = new Material(Shader.Find("Custom/Outlight"));
  63. mat.SetColor("_LightColor", color);
  64. mat.SetInt("_Size", 30);
  65. imgComp.material = mat;
  66. return RTF;
  67. }
  68. }