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;
}
}