using UnityEngine; using UnityEngine.EventSystems; namespace BrewMonster.UI { public class WorldMapClickHandler : MonoBehaviour, IPointerClickHandler { [Tooltip("The RectTransform of the Map Image (Usually this GameObject)")] private RectTransform mapRectTransform; [SerializeField] private RectTransform _hostPlayerPositionImage; public DlgWorldMap dlgWorldMap; // if true, user can click on the map to move the host player to the clicked position. // ideally we only enble this for testing/development. [SerializeField] private bool _enableClickToMove = true; // The host player player (0,0,0) is not at the center of the map. It usually has an offset that we have to calculate at Awake private Vector2 _hostPlayerOffsetPosition; private void Awake() { // Get the RectTransform of the map mapRectTransform = GetComponent(); CalculateHostPlayerOffsetPosition(); } private void CalculateHostPlayerOffsetPosition() { _hostPlayerOffsetPosition = _hostPlayerPositionImage.anchoredPosition; // if the max/min of the anchor is 0.5 0.5, then the host player is at the center of the map // however we have to calculate the offset of the player because it is not at the center of the map // we can calculate the offset by the max/min of the anchor var maxAnchor = _hostPlayerPositionImage.anchorMax; var minAnchor = _hostPlayerPositionImage.anchorMin; _hostPlayerOffsetPosition = new Vector2((maxAnchor.x - 0.5f) * mapRectTransform.rect.width, (maxAnchor.y - 0.5f) * mapRectTransform.rect.height); } // This triggers automatically when the user clicks/taps on this Image public void OnPointerClick(PointerEventData eventData) { if(!_enableClickToMove) return; Vector2 localCursorPosition; // Convert the screen click position to local anchored position inside the Map bool isConverted = RectTransformUtility.ScreenPointToLocalPointInRectangle( mapRectTransform, eventData.position, eventData.pressEventCamera, out localCursorPosition ); if (isConverted) { // convert the localCursorPosition to the local position of the host player position image localCursorPosition -= _hostPlayerOffsetPosition; dlgWorldMap.OnMapClicked(localCursorPosition); } } } }