效果:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UILink : MonoBehaviour
{
public GameObject Line;
public Transform mapContent;
public RawImage BeginUI;
public RawImage EndUI;
public RawImage EndUI2;
Vector2 BeginPos;
Vector2 targetPos;
Vector2 targetPos2;
private void Start()
{
BeginPos = BeginUI.rectTransform.localPosition;
targetPos = EndUI.rectTransform.localPosition;
targetPos2 = EndUI2.rectTransform.localPosition;
CreateLine(BeginPos, targetPos);
CreateLine(targetPos, targetPos2);
}
public void CreateLine(Vector2 start, Vector2 end)
{
GameObject line = Instantiate(Line);
line.transform.SetParent(mapContent);
RectTransform rect = line.GetComponent<RectTransform>();
rect.localPosition = GetBetweenPoint(start, end);
rect.localRotation = Quaternion.AngleAxis(-GetAngle(start, end), Vector3.forward);
rect.localScale = new Vector3(20, 1, 1);
var distance = Vector2.Distance(end, start);
rect.sizeDelta = new Vector2(5, Math.Max(1, distance));
line.transform.SetAsFirstSibling();
}
public float GetAngle(Vector2 start, Vector2 end)
{
var dir = end - start;
var dirV2 = new Vector2(dir.x, dir.y);
var angle = Vector2.SignedAngle(dirV2, Vector2.down);
return angle;
}
private Vector2 GetBetweenPoint(Vector2 start, Vector2 end)
{
float distance = end.y - start.y;
float y = start.y + distance / 2;
float x = start.x;
if (start.x != end.x)
{
float k = (end.y - start.y) / (end.x - start.x);
float b = start.y - k * start.x;
x = (y - b) / k;
}
Vector2 point = new Vector2(x, y);
return point;
}
}
|