Unity GL Draw Line 画线

using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine;

public class DrawRectOperate : MonoBehaviour
{
    static DrawRectOperate _instance;

    private Material m_material;
    private float3 m_startPos;
    private float3 m_endPos;

    private bool Drow = false;

    public static DrawRectOperate Instance()
    {
        return _instance;
    }

    private void Awake()
    {
        _instance = this;
    }

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Drow = true;
            m_startPos = GetScreenTouchPos();
        }

        if (Drow)
        {
            m_endPos = GetScreenTouchPos();
        }

        if (Input.GetMouseButtonUp(0))
        {
            Drow = false;
            m_startPos = 0;
            m_endPos = 0;
            DrawAreaByPos();
        }
    }

    private void OnRenderObject()
    {
        if(Drow)
        {
            DrawAreaByPos();
        }
    }

    void DrawAreaByPos()
    {
        DrawArea(new Rect(math.min(m_startPos.x, m_endPos.x), math.min(m_startPos.y, m_endPos.y),
            math.max(m_startPos.x, m_endPos.x) - math.min(m_startPos.x, m_endPos.x),
            math.max(m_startPos.y, m_endPos.y) - math.min(m_startPos.y, m_endPos.y)));
    }

    void DrawArea(Rect rect)
    {
        Begin();

        GL.Vertex3(rect.xMin / Screen.width, rect.yMin / Screen.height, 0);
        GL.Vertex3(rect.xMin / Screen.width, rect.yMax / Screen.height, 0);

        GL.Vertex3(rect.xMin / Screen.width, rect.yMax / Screen.height, 0);
        GL.Vertex3(rect.xMax / Screen.width, rect.yMax / Screen.height, 0);

        GL.Vertex3(rect.xMax / Screen.width, rect.yMax / Screen.height, 0);
        GL.Vertex3(rect.xMax / Screen.width, rect.yMin / Screen.height, 0);

        GL.Vertex3(rect.xMax / Screen.width, rect.yMin / Screen.height, 0);
        GL.Vertex3(rect.xMin / Screen.width, rect.yMin / Screen.height, 0);

        End();
    }

    void Begin()
    {
        if (m_material == null)
            m_material = new Material(Shader.Find("Unlit/Color"));
        m_material.SetPass(0);
        GL.LoadOrtho();
        GL.Begin(GL.LINES);
        m_material.SetColor("_Color", Color.green);
    }

    void End()
    {
        GL.End();
    }

    public static Vector3 GetScreenTouchPos()
    {
        return GetTouchPosition();
    }

    public static Vector3 GetTouchPosition()
    {
#if UNITY_EDITOR || UNITY_STANDALONE_WIN
        return Input.mousePosition;
#else
         return Input.touches[0].position;
#endif
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值