Using line renderer & ScreenToWorldPoint in a 2D Application

I am having an issue with using a LineRenderer to display lines drawn on screen. I am trying to use the mouse position to draw the lines. It works and draws the line from where the mouse was clicked to where the mouse button was released, but there is one small thing messing me up. When i click the mouse to start the line, for just a split second, probably a single frame, the start point is the center of my screen (probably something to do with the camera position at (0,0,-10). I am having trouble figuring out why the line is initially started from this point. As i said, it’s only for about 1 frame then the line start point jumps to wherever i clicked my mouse as i want it to. I’m sure this is some rookie mistake i made, probably something to do with how i am trying to get the mouse location. Any help is greatly appreciated. I have written a small script (just attach it to a camera) to demonstrate the issue:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LineTest : MonoBehaviour {
    private LineRenderer line;
    private Vector3 mouseLoc;
    private bool canDrawLine = true;
    private bool drawingLine;
    private int lineCount = 0;

    void Update ()
    {
        mouseLoc = Camera.main.ScreenToWorldPoint (Input.mousePosition) + new Vector3 (0,0,10.0f);

        if (Input.GetMouseButtonDown (0) && !drawingLine) {
            createLine ();
            lineCount++;
            line.SetPosition (0, mouseLoc);
            drawingLine = true;
            canDrawLine = false;
        } else if (Input.GetMouseButton (0) && drawingLine) {
            line.SetPosition (1, mouseLoc);
            canDrawLine = false;
        } else if (Input.GetMouseButtonUp (0) && drawingLine) {
            drawingLine = false;
            line.SetPosition (1, mouseLoc);
            canDrawLine = true;
        }
    }

    private void createLine() // create empty GameObject & add component Line Renderer
    {
        line = new GameObject("Line" + lineCount.ToString()).AddComponent<LineRenderer>();
        line.startWidth = line.endWidth = 0.05f;
        line.numPositions = 2;
    }
}

in GetMouseButtonDown, also call “line.SetPosition (1, mouseLoc);”.

the line you’re seeing is because the 2nd point isn’t set til the next frame

1 Like

It’s because you’re setting the line to have 2 points, but you only set the first point initially. The second one defaults to (0,0,0). Then on the second update, you set the second position.

Thank you very much @JoshuaMcKenzie & @LiterallyJeff !!

1 Like