0%

计算敌人在屏幕中的位置

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CArrowLockAt : MonoBehaviour
{
public Transform target; //目标
public Transform self; //自己
public Image RoundScope;//指定为圆
public float direction; //箭头旋转的方向,或者说角度,只有正的值
public Vector3 u; //叉乘结果,用于判断上述角度是正是负

float devValue =100f; //离屏边缘距离


Quaternion originRot; //箭头原角度

// 初始化
void Start()
{
originRot = transform.rotation;
}

void Update()
{


// 计算向量和角度
Vector3 forVec = self.forward; //计算本物体的前向量
Vector3 angVec = (target.position - self.position).normalized; //本物体和目标物体之间的单位向量

#region 求指向
Vector3 targetVec = Vector3.ProjectOnPlane(angVec - forVec, forVec).normalized; //这步很重要,将上述两个向量计算出一个代表方向的向量后投射到本身的xy平面
Vector3 originVec = self.up;

direction = Vector3.Dot(originVec, targetVec); //再跟y轴正方向做点积和叉积,就求出了箭头需要旋转的角度和角度的正负

u = Vector3.Cross(originVec, targetVec);

direction = Mathf.Acos(direction) * Mathf.Rad2Deg; //转换为角度

u = self.InverseTransformDirection(u); //叉积结果转换为本物体坐标

// 给与旋转值
transform.rotation = originRot * Quaternion.Euler(new Vector3(0f, 0f, direction * (u.z > 0 ? 1 : -1)));
#endregion


// 计算当前物体在屏幕上的位置
Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(Camera.main,target.position);
#region 求在圆边位置
//圆半径
float range = (RoundScope.rectTransform.sizeDelta.y / 2) - 30;
//目标位置
Vector3 cc = RoundScope.transform.position + Vector3.ProjectOnPlane((target.position - self.position) - self.forward, self.forward) * range;
#endregion
// 不在屏幕内的情况
if (screenPos.x < devValue || screenPos.x > Screen.width - devValue || screenPos.y < devValue || screenPos.y > Screen.height - devValue || Vector3.Dot(forVec, angVec) < 0)
{
if (range < Vector3.Distance(cc, RoundScope.rectTransform.position))
{
transform.position = (cc - RoundScope.transform.position).normalized * range + RoundScope.transform.position;
}
else
{
transform.position = cc;
}
}
else // 在屏幕内的情况
{
transform.Rotate(0, 90, -45);
}
}
}