| | 1 | | using DCLServices.MapRendererV2.MapCameraController; |
| | 2 | | using System; |
| | 3 | | using UnityEngine; |
| | 4 | |
|
| | 5 | | namespace DCLServices.MapRendererV2.ConsumerUtils |
| | 6 | | { |
| | 7 | | /// <summary> |
| | 8 | | /// Updates Map Camera Controller's position accordingly to the player position |
| | 9 | | /// </summary> |
| | 10 | | public struct MapRendererTrackPlayerPosition : IDisposable |
| | 11 | | { |
| | 12 | | private const float SQR_DISTANCE_TOLERANCE = 0.01f; |
| | 13 | |
|
| | 14 | | private readonly IMapCameraController cameraController; |
| | 15 | | private readonly BaseVariable<Vector3> playerWorldPosition; |
| | 16 | |
|
| | 17 | | private Vector3 lastPlayerPosition; |
| | 18 | |
|
| | 19 | | public MapRendererTrackPlayerPosition(IMapCameraController cameraController, BaseVariable<Vector3> playerWorldPo |
| | 20 | | { |
| 10 | 21 | | this.cameraController = cameraController; |
| 10 | 22 | | this.playerWorldPosition = playerWorldPosition; |
| | 23 | |
|
| 10 | 24 | | lastPlayerPosition = Vector3.positiveInfinity; |
| | 25 | |
|
| 10 | 26 | | OnPlayerPositionChanged(Vector3.positiveInfinity, playerWorldPosition.Get()); |
| | 27 | |
|
| 10 | 28 | | playerWorldPosition.OnChange += OnPlayerPositionChanged; |
| 10 | 29 | | } |
| | 30 | |
|
| | 31 | | private void OnPlayerPositionChanged(Vector3 oldPos, Vector3 newPos) |
| | 32 | | { |
| 489 | 33 | | if (Vector3.SqrMagnitude(newPos - lastPlayerPosition) < SQR_DISTANCE_TOLERANCE) |
| 193 | 34 | | return; |
| | 35 | |
|
| 296 | 36 | | lastPlayerPosition = newPos; |
| 296 | 37 | | cameraController.SetPosition(GetPlayerCentricCoords(newPos)); |
| 296 | 38 | | } |
| | 39 | |
|
| | 40 | | public static Vector2 GetPlayerCentricCoords(Vector3 playerPosition) |
| | 41 | | { |
| 296 | 42 | | var newCoords = DCL.Helpers.Utils.WorldToGridPositionUnclamped(playerPosition); |
| 296 | 43 | | return GetPlayerCentricCoords(newCoords); |
| | 44 | | } |
| | 45 | |
|
| | 46 | | public static Vector2 GetPlayerCentricCoords(Vector2 playerCoords) |
| | 47 | | { |
| | 48 | | // quick hack to align with `CoordsToPositionWithOffset` and the pivot |
| 306 | 49 | | return playerCoords - Vector2.one; |
| | 50 | | } |
| | 51 | |
|
| | 52 | | public void Dispose() |
| | 53 | | { |
| 10 | 54 | | playerWorldPosition.OnChange -= OnPlayerPositionChanged; |
| 10 | 55 | | } |
| | 56 | | } |
| | 57 | | } |