using System.Collections; using System.Collections.Generic; using UnityEngine; public class FollowItemView : MonoBehaviour { [SerializeField] private FollowItemConfig MTarget; private LineRenderer mLine; private float RayCd = 0.0f;//找新的位置 private float lastCheckTime = float.MinValue; void Start() { mLine = this.GetComponent(); } private void LateUpdate() { RefreshPoint(); } void OnDrawGizmos() { var direction = transform.TransformDirection(Vector3.up) * 5; // 在物体的前方绘制一个5米长的线 Gizmos.color = Color.green; Gizmos.DrawRay(transform.position, direction); Gizmos.color = Color.red; Gizmos.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 5); } private Transform LookTarget { get { return Camera.main.transform; } } //这个点不能在别人家的碰撞框里面 //这个点不能被射线遮挡 //这个点和模型的中心点 private Vector3 Point; private void CheckVert() { Vector3[] vertices = MTarget.TriggerCol.sharedMesh.vertices; Vector3 pos; float maxAngle = float.MinValue; Vector3 selectPos = this.transform.position; float checkAngle; for (int i = 0; i < vertices.Length; i++) { pos = MTarget.transform.TransformPoint(vertices[i] * MTarget.TriggerCol.transform.localScale.x); if (!CameraZhedang(pos)) { Debug.DrawLine(MTarget.transform.position, pos, Color.red); checkAngle = GetAngle(pos); if (maxAngle < checkAngle && checkAngle < 90) { maxAngle = checkAngle; selectPos = pos; } } } Point = selectPos; } private Vector3[] LinePoints = new Vector3[3]; private void RefreshPoint() { if (Time.realtimeSinceStartup >= lastCheckTime + RayCd) { lastCheckTime = Time.realtimeSinceStartup; CheckVert(); this.transform.position = Point; LinePoints[0] = this.transform.position; LinePoints[2] = MTarget.ClosePoint(this.transform.position); ; LinePoints[1] = Vector3.Lerp(this.transform.position, LinePoints[2], 0.3f); LinePoints[1].y = this.transform.position.y; this.mLine.SetPositions(LinePoints); } this.transform.LookAt(LookTarget); } private bool CameraZhedang(Vector3 pos) { Ray mRay = new Ray(LookTarget.position, (pos - LookTarget.position)); RaycastHit hitInfo; if (Physics.Raycast(mRay, out hitInfo,100, 10)) { return true; } return false; } private float GetAngle(Vector3 pos) { return Vector3.Angle((MTarget.transform.position - pos), (LookTarget.transform.position - pos)); } }