Files
test/Assets/PerfectWorld/Scripts/UI/WorldMap/WorldMapClickHandler.cs
T
2026-04-24 15:33:39 +07:00

60 lines
2.4 KiB
C#

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;
// 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<RectTransform>();
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)
{
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);
}
}
}
}