两点之间连接线段并保持
1.创建场景需要的物体
1.首先创建3个Image
Canvas的Resolution设置
2.开始配置位置和定位
2.将Line放到Start里面并居中,调节Line的Pivot
3.最终效果展示
3.重点来了 放置脚本 并赋值
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LineMovewithendpos : MonoBehaviour {
public Color Lincolor;
public int LineHeight;
public RectTransform Line;
public Transform startpos;
public Transform endpos;
void Start () {
}
// Update is called once per frame
void Update () {
Line.GetComponent<Image>().color = Lincolor;
Line.sizeDelta = new Vector2(Line.sizeDelta.x, LineHeight);
Line.sizeDelta = new Vector2((startpos.position - endpos.position).magnitude , LineHeight);
Line.transform.rotation = Quaternion.Euler(0, 0, angle_360(endpos.position, startpos.position));
}
float angle_360(Vector3 from_, Vector3 to_)
{
//两点的x、y值
float x = from_.x - to_.x;
float y = from_.y - to_.y;
//斜边长度
float hypotenuse = Mathf.Sqrt(Mathf.Pow(x, 2f) + Mathf.Pow(y, 2f));
//求出弧度
float cos = x / hypotenuse;
float radian = Mathf.Acos(cos);
//用弧度算出角度
float angle = 180 / (Mathf.PI / radian);
if (y < 0)
{
angle = -angle;
}
else if ((y == 0) && (x < 0))
{
angle = 180;
}
return angle;
}
}
出现分辨率问题
但是有个问题是根据屏幕分辨率不同,导致线段无法过长或过短
【2560X1440】
【1024X768】
计算分辨率屏幕长度计算为
屏幕分辨率.width/1920 为倍数
这里只精准到了后2位,如果计算更加精细 就多加0
float count = 1 ;
count = (float)(UnityEngine.Screen.width*1000/1920)/1000;
完整代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LineMovewithendpos : MonoBehaviour {
public Color Lincolor;
public int LineHeight;
public RectTransform Line;
public Transform startpos;
public Transform endpos;
void Start () {
}
// Update is called once per frame
void Update()
{
Line.GetComponent<Image>().color = Lincolor;
Line.sizeDelta = new Vector2(Line.sizeDelta.x, LineHeight);
float count = 1;
count = (float)(UnityEngine.Screen.width * 1000 / 1920) / 1000;
Line.sizeDelta = new Vector2((startpos.position - endpos.position).magnitude / count, LineHeight);
Line.transform.rotation = Quaternion.Euler(0, 0, angle_360(endpos.position, startpos.position));
}
float angle_360(Vector3 from_, Vector3 to_)
{
//两点的x、y值
float x = from_.x - to_.x;
float y = from_.y - to_.y;
//斜边长度
float hypotenuse = Mathf.Sqrt(Mathf.Pow(x, 2f) + Mathf.Pow(y, 2f));
//求出弧度
float cos = x / hypotenuse;
float radian = Mathf.Acos(cos);
//用弧度算出角度
float angle = 180 / (Mathf.PI / radian);
if (y < 0)
{
angle = -angle;
}
else if ((y == 0) && (x < 0))
{
angle = 180;
}
return angle;
}
}
大功告成!