ParallelCamera.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. using UnityEngine;
  2. namespace XGame.Framework.Map
  3. {
  4. /// <summary>
  5. /// 平行相机跟随范围
  6. /// 相机跟随目标限制在该范围内
  7. /// </summary>
  8. [RequireComponent(typeof(Camera))]
  9. public class ParallelCamera : MonoBehaviour
  10. {
  11. private struct Positions
  12. {
  13. public Vector3 leftDown;
  14. public Vector3 leftUp;
  15. public Vector3 rightDown;
  16. public Vector3 rightUp;
  17. public Vector3 CenterUp => (leftUp + rightUp) * 0.5f;
  18. public Vector3 CenterDown => (leftDown + rightDown) * 0.5f;
  19. public override string ToString()
  20. {
  21. return $"Positions leftDown:{leftDown} leftUp:{leftUp} rightDown:{rightDown} rightUp:{rightUp}";
  22. }
  23. }
  24. /// <summary>
  25. /// 目标平面垂直于相机的直线距离
  26. /// </summary>
  27. [SerializeField]
  28. private float _distance = 16;
  29. /// <summary>
  30. /// 可移动区域相对于视口的缩放
  31. /// </summary>
  32. [SerializeField]
  33. private Vector2 _viewportScale = Vector2.one;
  34. /// <summary>
  35. /// 可移动区域对齐点
  36. /// </summary>
  37. [SerializeField]
  38. private Vector2 _viewportPivot = Vector2.one * 0.5f;
  39. /// <summary>
  40. /// 指定距离对应的视口大小
  41. /// 下负上正,左负右正
  42. /// 不可修改
  43. /// </summary>
  44. //[SerializeField]
  45. private Rect _viewportRect;
  46. /// <summary>
  47. /// 目标移动区域
  48. /// 下负上正,左负右正
  49. /// 不可修改
  50. /// </summary>
  51. //[SerializeField]
  52. private Rect _targetRect;
  53. //[SerializeField]
  54. private Camera _camera;
  55. //[SerializeField]
  56. private IParallelTarget _target;
  57. //[SerializeField]
  58. private Vector3 _offsetUp;
  59. //[SerializeField]
  60. private Vector3 _offsetDown;
  61. /// <summary>
  62. /// 目标的屏幕区域
  63. /// 左下(0,0),右上(width,height)
  64. /// </summary>
  65. private Rect _screenRect;
  66. /// <summary>
  67. /// 显示区域顶部中心位置转世界坐标
  68. /// </summary>
  69. /// <returns></returns>
  70. public Vector3 TopCenterToWorldPosition()
  71. {
  72. var screenPos = _screenRect.center;
  73. screenPos.y = _screenRect.yMax;
  74. return _camera.ScreenToWorldPoint(screenPos);
  75. }
  76. public IParallelTarget Target
  77. {
  78. get => _target;
  79. set
  80. {
  81. if (_target != value)
  82. {
  83. _target = value;
  84. OnSetTarget();
  85. }
  86. }
  87. }
  88. private void Awake()
  89. {
  90. _camera = GetComponent<Camera>();
  91. CalculateViewport();
  92. }
  93. //private void LateUpdate()
  94. //{
  95. // if (_target != null)
  96. // {
  97. // if (_offset == Vector3.zero)
  98. // {
  99. // _offset = transform.position - _target.position;
  100. // }
  101. // transform.position = _target.position + _offset;
  102. // //Debug.Log($"LateUpdate distance: {PointToPlaneDistance(transform.position, target.position, Vector3.back)}");
  103. // }
  104. //}
  105. public void OnLateUpdate(int millisecond)
  106. {
  107. if (_target == null)
  108. return;
  109. var tarPosition = _target.Position;
  110. var tarScreenPos = _camera.WorldToScreenPoint(tarPosition);
  111. if (_target.IsMoving)
  112. {
  113. var moveDir = _target.MoveDir;
  114. if (tarScreenPos.y > _screenRect.yMax && moveDir.y > 0)
  115. { // 小于
  116. //Debug.Log($"OnLateUpdate Up :{tarScreenPos} _offsetUp:{_offsetUp}");
  117. transform.position = tarPosition + _offsetUp;
  118. }
  119. else if (tarScreenPos.y < _screenRect.y && moveDir.y < 0)
  120. {
  121. //Debug.Log($"OnLateUpdate Down :{tarScreenPos} _offsetDown:{_offsetDown}");
  122. transform.position = tarPosition + _offsetDown;
  123. }
  124. }
  125. else
  126. {// 没有移动
  127. if (tarScreenPos.y > _screenRect.y)
  128. { // 自动移动到显示区域底部
  129. var pos = transform.position;
  130. pos.y += millisecond * 0.001f * 2;
  131. transform.position = pos;
  132. }
  133. }
  134. //Debug.Log($"OnLateUpdate Screen:{tarScreenPos} tarPosition:{tarPosition}");
  135. }
  136. private void OnSetTarget()
  137. {
  138. if (_target == null)
  139. return;
  140. //_offset = transform.position - _target.position;
  141. _distance = PointToPlaneDistance(transform.position, _target.Position, Vector3.back);
  142. CalculateViewport();
  143. }
  144. private void CalculateViewport()
  145. {
  146. //Debug.Log($"Camera pixelRect:{_camera.pixelRect} rect:{_camera.rect} pixelWidth:{_camera.pixelWidth} pixelHeight:{_camera.pixelHeight}");
  147. var fovRadians = Mathf.Deg2Rad * _camera.fieldOfView; //fov从度数转弧度
  148. var viewportH = 2 * Mathf.Tan(fovRadians * 0.5f) * _distance;
  149. var viewportW = viewportH * _camera.aspect;
  150. _viewportRect = new Rect(-viewportW * 0.5f, -viewportH * 0.5f, viewportW, viewportH);
  151. _targetRect = new Rect(_viewportRect);
  152. _targetRect.size *= _viewportScale;
  153. _targetRect.center = _viewportRect.center + (_viewportPivot - Vector2.one * 0.5f) * _targetRect.size;
  154. var positions = RectToWorldPositions(_targetRect);
  155. _offsetUp = transform.position - positions.CenterUp;
  156. _offsetDown = transform.position - positions.CenterDown;
  157. var leftDown = _camera.WorldToScreenPoint(positions.leftDown);
  158. var rightUp = _camera.WorldToScreenPoint(positions.rightUp);
  159. _screenRect = new Rect(leftDown.x, leftDown.y, rightUp.x - leftDown.x, rightUp.y - leftDown.y);
  160. //Debug.Log($"World leftDown:{positions.leftDown} leftUp:{positions.leftUp} rightDown:{positions.rightDown} rightUp:{positions.rightUp}");
  161. //Log.Debug($"Screen leftDown:{leftDown} rightUp:{rightUp} screenRect:{_screenRect}");
  162. }
  163. private Positions RectToWorldPositions(Rect rect)
  164. {
  165. var normal = transform.forward;
  166. var center = transform.position + normal * _distance;
  167. var halfSize = rect.size * 0.5f;
  168. var offset = rect.center;
  169. var xAxis = Vector3.Normalize(Vector3.Cross(normal, Vector3.up));
  170. //Debug.Log($"center:{center} halfSize:{halfSize} offset:{offset} xAxis:{xAxis}");
  171. if (xAxis == Vector3.zero)
  172. { //预防当前方向与Y轴平行
  173. xAxis = Vector3.Cross(normal, Vector3.right);
  174. }
  175. var yAxis = Vector3.Cross(normal, xAxis);
  176. center = center - xAxis * offset.x - yAxis * offset.y;
  177. var positions = new Positions();
  178. positions.leftDown = center + xAxis * halfSize.x + yAxis * halfSize.y;
  179. positions.leftUp = center + xAxis * halfSize.x - yAxis * halfSize.y;
  180. positions.rightDown = center - xAxis * halfSize.x + yAxis * halfSize.y;
  181. positions.rightUp = center - xAxis * halfSize.x - yAxis * halfSize.y;
  182. //Log.Debug(positions);
  183. return positions;
  184. }
  185. /// <summary>
  186. /// 计算点到平面的垂直距离
  187. /// 法线向量不能为零
  188. /// </summary>
  189. /// <param name="point">待计算距离的点</param>
  190. /// <param name="pointOnPlane">平面上的一个点</param>
  191. /// <param name="planeNormal">平面的法线向量</param>
  192. /// <returns></returns>
  193. private float PointToPlaneDistance(Vector3 point, Vector3 pointOnPlane, Vector3 planeNormal)
  194. {
  195. var distance = Vector3.Dot(planeNormal, (point - pointOnPlane)) / planeNormal.magnitude;
  196. return distance;
  197. }
  198. public Vector3 WorldToScreenPoint(Vector3 point)
  199. {
  200. return _camera.WorldToScreenPoint(point);
  201. }
  202. #if UNITY_EDITOR
  203. void OnDrawGizmos()
  204. { //下负上正,左负右正
  205. //if (Physics.Raycast(transform.position, transform.forward, out var hitInfo))
  206. //{
  207. //}
  208. _camera = GetComponent<Camera>();
  209. CalculateViewport();
  210. var positions_1 = RectToWorldPositions(_viewportRect);
  211. Gizmos.color = Color.blue;
  212. Gizmos.DrawLine(positions_1.leftDown, positions_1.rightDown);
  213. Gizmos.DrawLine(positions_1.rightDown, positions_1.rightUp);
  214. Gizmos.DrawLine(positions_1.rightUp, positions_1.leftUp);
  215. Gizmos.DrawLine(positions_1.leftUp, positions_1.leftDown);
  216. Gizmos.color = Color.red;
  217. var positions_2 = RectToWorldPositions(_targetRect);
  218. Gizmos.DrawLine(positions_2.leftDown, positions_2.rightDown);
  219. Gizmos.DrawLine(positions_2.rightDown, positions_2.rightUp);
  220. Gizmos.DrawLine(positions_2.rightUp, positions_2.leftUp);
  221. Gizmos.DrawLine(positions_2.leftUp, positions_2.leftDown);
  222. Gizmos.DrawLine(transform.position, positions_2.CenterUp);
  223. Gizmos.DrawLine(transform.position, positions_2.CenterDown);
  224. //Gizmos.color = Color.green;
  225. //Vector3[] frustumCorners = new Vector3[4];
  226. //camera.CalculateFrustumCorners(new Rect(0, 0, 1, 1), distance, Camera.MonoOrStereoscopicEye.Mono, frustumCorners);
  227. //var offsetZ = transform.position.z;
  228. //for ( int i = 0; i < frustumCorners.Length; i++)
  229. //{
  230. // var pos = frustumCorners[i];
  231. // pos.z += offsetZ;
  232. // frustumCorners[i] = pos;
  233. //}
  234. //Gizmos.DrawLine(frustumCorners[0], frustumCorners[1]);
  235. //Gizmos.DrawLine(frustumCorners[1], frustumCorners[2]);
  236. //Gizmos.DrawLine(frustumCorners[2], frustumCorners[3]);
  237. //Gizmos.DrawLine(frustumCorners[3], frustumCorners[0]);
  238. //Gizmos.DrawFrustum(transform.position, fovRadians, camera.farClipPlane, camera.nearClipPlane, camera.aspect);
  239. //var ray = camera.ScreenPointToRay(Vector3.zero);
  240. //Gizmos.DrawRay(ray);
  241. //Debug.Log($"PointToScreen LD:{PointToScreen(leftDown)} LU:{PointToScreen(leftUp)} RD:{PointToScreen(rightDown)} RU:{PointToScreen(rightUp)}");
  242. }
  243. #endif
  244. }
  245. }