- Home /
Drawing lines from mouse position
How do you draw lines from mouse position using lineRenderer?
For some reason, I cannot seem to get the line to be oriented correctly relative to the camera.
You mean to create lines planar to the screen? Or create lines in 3d space that are billboarded to the screen? You might need to post some of your code so we can see what you're trying to achieve.
From mouse position to where? If it's from the camera, you'd never see the line (because by definition it'd be pointing directly away from the camera)
Answer by Rod-Green · Nov 09, 2011 at 01:02 AM
Tested and updated to fix errors
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(LineRenderer))]
public class LineRendererTest : MonoBehaviour
{
List<Vector3> linePoints = new List<Vector3>();
LineRenderer lineRenderer;
public float startWidth = 1.0f;
public float endWidth = 1.0f;
public float threshold = 0.001f;
Camera thisCamera;
int lineCount = 0;
Vector3 lastPos = Vector3.one * float.MaxValue;
void Awake()
{
thisCamera = Camera.main;
lineRenderer = GetComponent<LineRenderer>();
}
void Update()
{
Vector3 mousePos = Input.mousePosition;
mousePos.z = thisCamera.nearClipPlane;
Vector3 mouseWorld = thisCamera.ScreenToWorldPoint(mousePos);
float dist = Vector3.Distance(lastPos, mouseWorld);
if(dist <= threshold)
return;
lastPos = mouseWorld;
if(linePoints == null)
linePoints = new List<Vector3>();
linePoints.Add(mouseWorld);
UpdateLine();
}
void UpdateLine()
{
lineRenderer.SetWidth(startWidth, endWidth);
lineRenderer.SetVertexCount(linePoints.Count);
for(int i = lineCount; i < linePoints.Count; i++)
{
lineRenderer.SetPosition(i, linePoints[i]);
}
lineCount = linePoints.Count;
}
}
this assumes you've defined a 'lineRenderer' property and also that you're using C#.. you didn't specify so I went with what I like ;)
Yes, I tried feeding a var like mouseWorld into lineRenderer.SetPosition, however the line seems drawn from the origin each time rather than continuously..
i guess it may be something with the camera clipplane - have you checked if the clip plane you set above will actually render a line continuous from mousepoint to mousepoint to mousepoint (etc), and not origin to mousepoint
I was using the wrong conversion.. should have been ScreenToWorldPoint..
Answer by volkan · Oct 29, 2012 at 10:51 AM
hi guys. i tried to modify this example so that when i clicked the mouse, line class adds a new GameObject every time and when i release line stays in world and when i click mouse again new line is added. how can i achieve this?
Your answer
Follow this Question
Related Questions
Gameobject is drawing a line render,when it's not supposed to ! 0 Answers
Draw a round-shaped line 3 Answers
How to get a LineRenderer to shoot from Gun Point to Mouse Position 1 Answer
How to Change Draw Order for GL.LINES? 0 Answers
attach drawing line using (LineRenderer) to moving background 0 Answers