注意,仅适用于UI,且Canvas必须是Camera模式,不能用在3D物体上,3D物体请使用LineRenender
先创建一个图片,将锚点固定在左边
然后在脚本中添加如下内容
public RectTransform startObj;//起点物体
public RectTransform endObj;//终点物体
public Camera camera;//Canvas的相机
private void CalcuateLine()//计算线的宽度和角度
{
if (startObj == null) return;
//设置长度和角度
Vector2 startPosition = Vector2.zero;
Vector2 endPosition = Vector2.zero;
//计算起点的世界坐标
startPosition = RectTransformUtility. WorldToScreenPoint(camera,startObj.position);
//计算终点的世界坐标
if (endObj != null)//如果有结束物体,以结束物体为终点
{
endPosition = RectTransformUtility.WorldToScreenPoint(camera, endObj.position);
}
else//如果没有结束物体,以鼠标位置为终点
{
endPosition = Input.mousePosition;
}
//计算长度
float dis = Vector2.Distance(startPosition,endPosition);
//设置长度
rectTransform.sizeDelta = new Vector2(dis,rectTransform.rect.height);
//计算角度
Vector3 dir = endPosition - startPosition;
float angle = Vector3.Angle(Vector3.right, dir);
Vector3 cross = Vector3.Cross(Vector3.right, dir);
float dirF = cross.z > 0 ? 1 : -1;
angle = angle * dirF;
//设置角度
rectTransform.localEulerAngles = new Vector3(0,0,angle);
//设置起点位置
Vector2 startLocalPostion = Vector2.zero;
RectTransformUtility.ScreenPointToLocalPointInRectangle(contentRectTransform, startPosition,camera,out startLocalPostion);
rectTransform.localPosition = startLocalPostion;
}