使用Image组件连接两个点,画直线短一截的原因

使用Image组件连接两个点,画直线短一截的原因

问题描述

我画图表的时候,发现有时候直线会莫名其妙短一截。后来才知道,是因为,使用了,求距离的函数,并且,如果你恰巧使用的屏幕分辨率和自己编辑器里的不一样,就会出bug。
像下面这样。

在这里插入图片描述
解决办法:
关键代码:float length = (dot2.transform.localPosition - dot1.transform.localPosition).magnitude;
做好之后是这样的
在这里插入图片描述

代码如下:

    public Image dot1;
    public Image dot2;
    public Image line;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            DrawPic();
        }
    }
    public void DrawPic()
    {
        line.transform.position = dot1.transform.position;

        var lirect = line.GetComponent<RectTransform>();

        float ange = SetAngle(dot1.transform.position, dot2.transform.position);
        lirect.transform.localEulerAngles = new Vector3(0, 0, ange);

        //方法一
        //float length = Vector3.Distance(dot1.transform.position, dot2.transform.position);

        //方法二
        float length = (dot2.transform.localPosition - dot1.transform.localPosition).magnitude;

        print(dot1.transform.position + "后:" + dot2.transform.position + ":" + length);

        lirect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, length);

    }
    private float SetAngle(Vector3 from, Vector3 to)
    {
        var dirA = to - from;
        var dirB = Vector3.right;
        float an = Vector3.Angle(dirA, dirB);
        float dir = (Vector3.Dot(dirA, Vector3.up) < 0 ? -1 : 1);
        an *= dir;
        return an;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱岗酸豆角吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值