56 lines
2.0 KiB
C#
56 lines
2.0 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
namespace DongWuYiXue.DaoNiaoShu
|
|
{
|
|
public class DrawLineTool : MonoBehaviour
|
|
{
|
|
public Canvas canvas;
|
|
//线段
|
|
public RectTransform fingerLine;
|
|
[HideInInspector]
|
|
public RectTransform start;
|
|
[HideInInspector]
|
|
public RectTransform end;
|
|
private static DrawLineTool instance;
|
|
private void Awake()
|
|
{
|
|
instance = this;
|
|
}
|
|
|
|
//针对手指位置和对应UI控件之间的连线需要转换坐标处理
|
|
private RectTransform SetLine(Vector3 startPos, Vector3 endPos, Color color, RectTransform lineParent)
|
|
{
|
|
RectTransform line = Instantiate(fingerLine, lineParent);
|
|
if (color != null)
|
|
line.GetComponent<Image>().color = color;
|
|
line.gameObject.SetActive(true);
|
|
line.pivot = new Vector2(0, 0.5f);
|
|
line.position = startPos;
|
|
line.eulerAngles = new Vector3(0, 0, GetAngle(startPos, endPos));
|
|
line.sizeDelta = new Vector2(GetDistance(startPos, endPos), fingerLine.sizeDelta.y);
|
|
return line;
|
|
}
|
|
//对外开放的静态方法,方便直接调用
|
|
public static GameObject DrawLine(Vector3 startPos, Vector3 endPos, Color color, RectTransform lineParent)
|
|
{
|
|
return instance.SetLine(startPos, endPos, color, lineParent).gameObject;
|
|
}
|
|
private float GetAngle(Vector3 startPos, Vector3 endPos)
|
|
{
|
|
Vector3 dir = endPos - startPos;
|
|
float angle = Vector3.Angle(Vector3.right, dir);
|
|
Vector3 cross = Vector3.Cross(Vector3.right, dir);
|
|
float dirF = cross.z > 0 ? 1 : -1;
|
|
angle = angle * dirF;
|
|
return angle;
|
|
}
|
|
private float GetDistance(Vector3 startPos, Vector3 endPos)
|
|
{
|
|
float distance = Vector3.Distance(endPos, startPos);
|
|
return distance * 1 / canvas.transform.localScale.x;
|
|
}
|
|
}
|
|
} |