【Unity】鼠标指向某物体,在其上显示物体的名字等等等等信息

时间:2023-03-10 01:42:50
【Unity】鼠标指向某物体,在其上显示物体的名字等等等等信息

之前一直用NGUI HUD Text插件做这个功能,感觉一个小功能就导一个插件进来简直丧心病狂。然后就自己写了一个~

 Camera cam;//用于发射射线的相机
Camera UIcam;//UI层的相机 Vector3 mp;//鼠标位置 Transform targetTransform;//点选的物体
public UILabel Lab; void Start ()
{
cam =this.GetComponent<Camera>();
UIcam = GameObject.Find("Camera").GetComponent<Camera>();
Lab = GameObject.Find("Label").GetComponent<UILabel>();
} void Update()
{
if (TarRaycast()) //判断鼠标是否指在某物体上
{
//这里转换坐标的时候我用的是“指定物体y轴方向向上0.3f处”,当然只是大体保证了匹配位置,最好的方式是手动指定,即提前手动拖一个空物体至“有需要点击的物体”下,固定其合适位置,然后坐标用这个空物体的~
Vector3 pos = cam.WorldToViewportPoint(targetTransform.position + new Vector3(, targetTransform.localScale.y / + 0.3f, ));
Lab.transform.position = UIcam.ViewportToWorldPoint(pos);
Lab.text = targetTransform.name;
}
}
//射线检测部分,不懂可看我之前的文章~
public bool TarRaycast()
{
Lab.text = null;
mp = Input.mousePosition;
targetTransform = null;
if (cam != null)
{
RaycastHit hitInfo;
Ray ray = cam.ScreenPointToRay(new Vector3(mp.x, mp.y, 0f));
if (Physics.Raycast(ray.origin, ray.direction, out hitInfo))
{
targetTransform = hitInfo.collider.transform;
return true;
}
}
return false; }
}