Mouse position to world coordinate position.

Hey guys,

I’m trying to drag a Line Renderer from a collider to the current mouse position. I’m getting weird results as the end poin does not follow the mouse pointer and is moving in the Y axis which I don’t want it to. Basically I want the mouse X to be the X position and Mouse Y to be the Z position of the end point.

Here’s what the code looks like so far:

var width = 0.06;
var c1 = Color.black;
var c2 = Color.yellow;
var start:Vector3;
var end:Vector3;
var mousePos:Vector3;

function Start () {

	
	var lineRenderer : LineRenderer = gameObject.AddComponent(LineRenderer);
	lineRenderer.material = new Material (Shader.Find("Particles/Additive"));
	lineRenderer.SetColors(c1,c2);
	lineRenderer.useWorldSpace = true;
	lineRenderer.SetWidth(width, width);
	lineRenderer.SetVertexCount(2);
	start = transform.position;
	lineRenderer.SetPosition(0, start);
	lineRenderer.SetPosition(1, start);
	
	
}

function OnMouseDrag(){

		mousePos = Vector3(Input.mousePosition.x, Input.mousePosition.y);

		start = transform.position;
		end = Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x, 0.0, Input.mousePosition.y));
		//end = transform.InverseTransformPoint(start);
		//end = new Vector3(Input.mousePosition.x, 0.0, Input.mousePosition.y);
		var lineRenderer : LineRenderer = GetComponent(LineRenderer);
		lineRenderer.SetPosition(0, end);

}

What am I doing wrong?

Cheers!

have a look at Unity - Scripting API: Camera.ScreenToWorldPoint
it transforms your screen coordinates into world coordinates. i’m not sure how it handles depth. so you could also cast a ray of a certain length through the pixel of your mouse position and retrieve the end point.