ParallelCamera.cs 11 KB

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