Fast 2D lines

Can anybody suggest a way to draw fast 2D lines? I need them in screenspace, not 3D world space, for a specialized UI element.

GL and LineRenderer are in 3D space, so I don’t think they will work for what I need to do.

Do you need to have lines drawn on the screen while 3D is going on in the background with a moving camera? If so, you can use GL or LineRenderer, but draw the lines in the camera’s coordinate space (use transform.TransformPoint to convert camera-relative points to world points).

If you just need lines with a static camera, you can probably just position the camera so that it sees the XY plane (ie, the plane where the Z coordinate is zero). It’s worth noting that you can use a Vector2 anywhere that a Vector3 is expected - it will be converted directly to a Vector3 with Z set to zero. This can simplify some 2D geometry tasks.

GL.LINES works fine, like this shows. As mentioned, just convert 2D/3D as necessary. I used ViewportToWorldPoint so I could use normalized viewport coords for the 2D points, but you could use another system like screen coordinates if you wanted to.

–Eric

I’m trying to do this with the LineRenderer and this is what I have so far:

    LineRenderer Line;

    void Start()
    {
        Line = GetComponent<LineRenderer>();
        Line.SetWidth(1, 1);
        Line.SetVertexCount(2);
        Line.material.color = Color.white;
    }
    void Update()
    {
        Vector3 from = Camera.current.ViewportToWorldPoint(new Vector2(10, 10));
        Vector3 to = Camera.current.ViewportToWorldPoint(new Vector2(50, 50));

        Line.SetPosition(0, from);
        Line.SetPosition(1, to);
    }

This doesn’t give me the desired result though. I just need to be able to draw a simple 2D line in XY coordinate space, with (0,0) being top left and (screen.width, screen.height) bottom right. What do I have to change to make it work? Thanks :slight_smile:

You’re using viewport space, but you actually want screen space.

–Eric

Thanks for your reply, Eric!

I changed it to

        Vector3 from = activeCam.ScreenToWorldPoint(new Vector3(10, 10, activeCam.nearClipPlane));
        Vector3 to = activeCam.ScreenToWorldPoint(new Vector3(50, 50, activeCam.nearClipPlane));

And that seems to work. Just passing in a Vector2(50, 50) doesn’t work.

Now I’m stuck on something else: the line must be 1 pixel wide.

Line.SetWidth(0.0001f, 0.0001f);

This gives me a 1 pixel line, but I just picked these values randomly. Do you have an idea on what value to use?

Thanks again :smile: