93 lines
3.5 KiB
C#
93 lines
3.5 KiB
C#
using System.Collections.Generic;
|
|
using BlueWater.Npcs.Customers;
|
|
using BlueWater.Tycoons;
|
|
using Sirenix.OdinInspector;
|
|
using UnityEngine;
|
|
|
|
namespace BlueWater.Uis
|
|
{
|
|
public class IndicatorUi : MonoBehaviour
|
|
{
|
|
[SerializeField, Required]
|
|
private GameObject _uiIndicator;
|
|
|
|
[SerializeField]
|
|
private Vector2 _widthPadding;
|
|
|
|
[SerializeField]
|
|
private Vector2 _heightPadding;
|
|
|
|
private RectTransform _canvasRectTransform;
|
|
private CustomerManager _customerManager;
|
|
private Camera _mainCamera;
|
|
private Dictionary<Customer, GameObject> _customerindicators = new();
|
|
private int _screenWidth;
|
|
private int _screenHeight;
|
|
|
|
private void Start()
|
|
{
|
|
_canvasRectTransform = GetComponent<RectTransform>();
|
|
_customerManager = CustomerManager.Instance;
|
|
_mainCamera = TycoonCameraManager.Instance.MainCamera;
|
|
|
|
_customerManager.OnInstantiateCustomer += AddUiIndicator;
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
_customerManager.OnInstantiateCustomer -= AddUiIndicator;
|
|
}
|
|
|
|
private void LateUpdate()
|
|
{
|
|
_screenWidth = Screen.width;
|
|
_screenHeight = Screen.height;
|
|
|
|
foreach (var element in _customerindicators)
|
|
{
|
|
var customer = element.Key;
|
|
var indicator = element.Value;
|
|
if (!customer)
|
|
{
|
|
_customerindicators.Remove(customer);
|
|
Destroy(indicator.gameObject);
|
|
return;
|
|
}
|
|
var target = customer.BalloonUi.transform;
|
|
var screenPosition = _mainCamera.WorldToScreenPoint(target.position);
|
|
|
|
if (!target.gameObject.activeSelf)
|
|
{
|
|
indicator.SetActive(false);
|
|
continue;
|
|
}
|
|
|
|
if (screenPosition.z > 0 && screenPosition.x > 0 && screenPosition.x < _screenWidth && screenPosition.y > 0 && screenPosition.y < _screenHeight)
|
|
{
|
|
indicator.SetActive(false);
|
|
}
|
|
else
|
|
{
|
|
indicator.SetActive(true);
|
|
var clampedScreenPosition = screenPosition;
|
|
clampedScreenPosition.x = Mathf.Clamp(screenPosition.x, 0f + _widthPadding.x, _screenWidth - _widthPadding.y);
|
|
clampedScreenPosition.y = Mathf.Clamp(screenPosition.y, 0f + _heightPadding.x, _screenHeight - _heightPadding.y);
|
|
RectTransformUtility.ScreenPointToLocalPointInRectangle(_canvasRectTransform, clampedScreenPosition, _mainCamera, out var localPoint);
|
|
indicator.transform.localPosition = localPoint;
|
|
|
|
var cameraCenterPosition = new Vector3(_screenWidth * 0.5f, _screenHeight * 0.5f, screenPosition.z);
|
|
var direction = (screenPosition - cameraCenterPosition).normalized;
|
|
var angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
|
|
indicator.transform.localRotation = Quaternion.Euler(0f, 0f, angle - 90f);
|
|
}
|
|
}
|
|
}
|
|
|
|
private void AddUiIndicator(Customer customer)
|
|
{
|
|
var newUiIndicator = Instantiate(_uiIndicator, transform);
|
|
newUiIndicator.SetActive(false);
|
|
_customerindicators.Add(customer, newUiIndicator);
|
|
}
|
|
}
|
|
} |