Unity制作一条线的垂线

文章介绍了如何在Unity游戏引擎中使用C#编程实现UIImage的UI垂线和LineRenderer进行世界空间垂线的绘制,包括SetChuizhiImage和SetChuizhiLine方法的详细步骤。
摘要由CSDN通过智能技术生成
/// <summary>
/// 制作垂线
/// </summary>
public class MakeVertical : MonoBehaviour
{
    /// <summary>
    /// UIImage作UI垂线
    /// </summary>
    public RectTransform line;
    /// <summary>
    /// LineRender做世界垂线
    /// </summary>
    public LineRenderer perpendicularLineRenderer;

    void Start()
    {
        SetChuizhiImage(line, Vector3.right, new Vector3(250, 0));
        SetChuizhiLine(perpendicularLineRenderer, new Vector3(2, 3, -3), new Vector3(3, 1, 3), 10);
    }

    /// <summary>
    /// 设置Line垂线
    /// </summary>
    /// <param name="perpendicularLineRenderer">线</param>
    /// <param name="startPoint">被做垂线起点</param>
    /// <param name="endPoint">被做垂线终点</param>
    public void SetChuizhiLine(LineRenderer perpendicularLineRenderer, Vector3 startPoint, Vector3 endPoint, float mochang)
    {
        // 计算线b的起点和终点
        Vector3 direction = (endPoint - startPoint).normalized;
        Vector3 perpendicularDirection = new Vector3(-direction.y, direction.x, 0);
        Vector3 perpendicularStartPoint = endPoint;
        Vector3 perpendicularEndPoint = endPoint + perpendicularDirection * mochang;
        // 绘制线b
        perpendicularLineRenderer.startWidth = 0.005f;
        perpendicularLineRenderer.endWidth = 0.005f;
        perpendicularLineRenderer.positionCount = 2;
        perpendicularLineRenderer.material = new Material(Shader.Find("UI/Default"));
        perpendicularLineRenderer.SetPosition(0, perpendicularStartPoint);
        perpendicularLineRenderer.SetPosition(1, perpendicularEndPoint);
    }
    /// <summary>
    /// 设置UI垂线(line:过point点垂直与vector向量的直线)
    /// </summary>
    /// <param name="line">线</param>
    /// <param name="vector">被做垂直之前的向量</param>
    /// <param name="point">线的坐标</param>
    public void SetChuizhiImage(RectTransform line, Vector3 vector, Vector3 point)
    {
        Vector2 direction = vector.normalized;
        Vector2 perpendicularDirection = new Vector2(-direction.y, direction.x);
        Vector2 perpendicularStartPoint = point;
        line.anchoredPosition = perpendicularStartPoint;
        line.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(perpendicularDirection.y, perpendicularDirection.x) * Mathf.Rad2Deg);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值