1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class CArrowLockAt : MonoBehaviour { public Transform target; public Transform self; public Image RoundScope; public float direction; public Vector3 u;
float devValue =100f;
Quaternion originRot;
void Start() { originRot = transform.rotation; }
void Update() {
Vector3 forVec = self.forward; Vector3 angVec = (target.position - self.position).normalized;
#region 求指向 Vector3 targetVec = Vector3.ProjectOnPlane(angVec - forVec, forVec).normalized; Vector3 originVec = self.up;
direction = Vector3.Dot(originVec, targetVec);
u = Vector3.Cross(originVec, targetVec); direction = Mathf.Acos(direction) * Mathf.Rad2Deg;
u = self.InverseTransformDirection(u); transform.rotation = originRot * Quaternion.Euler(new Vector3(0f, 0f, direction * (u.z > 0 ? 1 : -1))); #endregion
Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(Camera.main,target.position); #region 求在圆边位置 float range = (RoundScope.rectTransform.sizeDelta.y / 2) - 30; Vector3 cc = RoundScope.transform.position + Vector3.ProjectOnPlane((target.position - self.position) - self.forward, self.forward) * range; #endregion if (screenPos.x < devValue || screenPos.x > Screen.width - devValue || screenPos.y < devValue || screenPos.y > Screen.height - devValue || Vector3.Dot(forVec, angVec) < 0) { if (range < Vector3.Distance(cc, RoundScope.rectTransform.position)) { transform.position = (cc - RoundScope.transform.position).normalized * range + RoundScope.transform.position; } else { transform.position = cc; } } else { transform.Rotate(0, 90, -45); } } }
|