using UnityEngine;
using UnityEngine.UI;
public class ArrowPointer : MonoBehaviour
{
public Transform target; // 目标物品的Transform
public RectTransform arrowRect; // UI箭头的RectTransform
public RectTransform panelRect; // 包含箭头的Panel的RectTransform
public Camera camera; // 主相机
public Vector2 arrowSize; // UI箭头的大小
public float minDistanceToHide = 1f; // 距离小于此值时隐藏箭头
void Update()
{
if (target != null && camera != null)
{
// 计算目标物品与相机之间的距离
float distanceToTarget = Vector3.Distance(target.position, camera.transform.position);
// 计算目标物品与相机之间的方向
Vector3 directionToTarget = (target.position - camera.transform.position).normalized;
// 检查是否朝向目标物体
bool isFacingTarget = Vector3.Dot(camera.transform.forward, directionToTarget) > 0;
// 如果距离小于1,且朝向目标物体,则隐藏UI箭头
if (distanceToTarget < minDistanceToHide && isFacingTarget)
{
arrowRect.gameObject.SetActive(false);
return;
}
// 显示UI箭头
arrowRect.gameObject.SetActive(true);
// 将目标物品的世界位置转换到屏幕位置
Vector3 screenPoint = camera.WorldToScreenPoint(target.position);
// 将屏幕位置转换到Panel的局部位置
Vector2 localPoint;
RectTransformUtility.ScreenPointToLocalPointInRectangle(panelRect, screenPoint, null, out localPoint);
// 计算箭头方向并旋转
Vector3 direction = screenPoint - new Vector3(Screen.width / 2, Screen.height / 2, 0);
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
arrowRect.localEulerAngles = new Vector3(0, 0, angle - 90); // 减去90度是因为默认箭头向上
// 调整箭头位置,确保箭头在Panel范围内且完整显示
AdjustArrowPosition(localPoint);
}
}
void AdjustArrowPosition(Vector2 localPoint)
{
// 确保箭头在Panel的边界内
float halfArrowWidth = arrowSize.x / 2f;
float halfArrowHeight = arrowSize.y / 2f;
float panelWidth = panelRect.rect.width;
float panelHeight = panelRect.rect.height;
// 计算箭头在Panel中的位置
Vector2 clampedPosition = new Vector2(
Mathf.Clamp(localPoint.x, -panelWidth / 2 + halfArrowWidth, panelWidth / 2 - halfArrowWidth),
Mathf.Clamp(localPoint.y, -panelHeight / 2 + halfArrowHeight, panelHeight / 2 - halfArrowHeight)
);
// 如果目标在左侧,将箭头放置在Panel的左边界
if (localPoint.x < -panelWidth / 2 + halfArrowWidth)
{
clampedPosition.x = -panelWidth / 2 + halfArrowWidth;
}
// 如果目标在右侧,将箭头放置在Panel的右边界
if (localPoint.x > panelWidth / 2 - halfArrowWidth)
{
clampedPosition.x = panelWidth / 2 - halfArrowWidth;
}
// 如果目标在上方或下方,将箭头放置在Panel的上下边界
if (localPoint.y < -panelHeight / 2 + halfArrowHeight)
{
clampedPosition.y = -panelHeight / 2 + halfArrowHeight;
}
if (localPoint.y > panelHeight / 2 - halfArrowHeight)
{
clampedPosition.y = panelHeight / 2 - halfArrowHeight;
}
// 设置箭头的位置
arrowRect.localPosition = clampedPosition;
}
}