public Transform Target; //追踪目标
public RectTransform TeammatesObj; //悬浮图标
private Vector2 player2DPosition;
private Vector2 TeammatesFrame = new Vector2(Screen.width * 0.5f - (Screen.height * 0.07f), Screen.height * 0.43f); //显示图标在窗口边缘的位置IEnumerator TeammatesIcon()
{ //悬浮边框图标显示队友位置//获得屏幕中心坐标
Vector2 sc = new Vector2(Screen.width, Screen.height) * 0.5f;
while (true)
{
player2DPosition = Camera.main.WorldToScreenPoint(Target.position);
if (player2DPosition.x > Screen.width - 20 | player2DPosition.x < +20 | player2DPosition.y > Screen.height - 20 | player2DPosition.y < +20) //只有目标在屏幕之外才会显示
{
Vector2 xy = Teammates2DPosition - sc;
float x = 0;
float y = 0;
float a = Vector2.Angle(Vector2.right, new Vector2(Mathf.Abs(xy.x), Mathf.Abs(xy.y)));
if (a < Vector2.Angle(Vector2.right, new Vector2(TeammatesFrame.x, TeammatesFrame.y)))
{
x = TeammatesFrame.x;
y = Mathf.Tan(a * Mathf.PI / 180) * TeammatesFrame.x;
}
else
{
x = Mathf.Tan((90 - a) * Mathf.PI / 180) * TeammatesFrame.y;
y = TeammatesFrame.y;
}
if (xy.x < 0)
{
x = -x;
}
if (xy.z < 0)
{
y = -y;
}
TeammatesObj.localPosition= new Vector3(x, y,-1 ); 获得悬浮窗位置
}
yield return new WaitForSeconds(0.1f);
}
}
unity 屏幕追踪显示目标
最新推荐文章于 2023-12-12 13:46:16 发布
该博客主要展示了一段代码,用于实现悬浮图标指示队友位置的功能。代码中定义了追踪目标和悬浮图标,通过计算屏幕中心坐标和目标的二维位置,判断目标是否在屏幕外,若在则计算悬浮窗位置,实现悬浮边框图标显示队友位置。

1286

被折叠的 条评论
为什么被折叠?



