How to draw a line with touch?

I am trying to draw a line with LineRenderer that follows the user’s finger movements. So far I have been unable to draw a line, let alone have it follow the user’s finger. I am coming from objective-c and I don’t know much javascript.

Here is the script I am using.

Draw.js:

var c1 : Color = Color.white;
var c2 : Color = Color.white;

var line : GameObject;

var lengthOfLineRenderer : int = 5;

function Update () {

var touchCount : int = 0;

if (Input.GetMouseButtonDown (0)) {

   touchCount++;

}

if (Input.touchCount == 1) {

if (Input.GetTouch(0).phase == TouchPhase.Moved) {

     var lineRenderer : LineRenderer = line.AddComponent(LineRenderer);
     lineRenderer.SetColors(c1, c2);
     lineRenderer.SetWidth(0.2,0.2);
     lineRenderer.SetVertexCount(lengthOfLineRenderer);
     lineRenderer.SetPosition(0, gameObject.transform.position);

}

}   

}

but nothing happens :frowning:

So, to start with, grab the example at:

http://unity3d.com/support/documentation/ScriptReference/LineRenderer.SetPosition.html

and check that you can get that working. It’ll be easiest to just see this running inside the editor. This will show you how to get lines drawn. Note that these lines are drawn in 3d space (and by default are in the coordinate space of the game object the LineRenderer component is attached to.) The LineRenderer does allow you to specify coordinates in world space, and that might be easier for you.

Next, when the user touches the screen you’ll want to figure out where they are touching, and generate a 3d position from that 2d position. This might be the hardest thing for you to work out. See:

http://unity3d.com/support/documentation/ScriptReference/Camera.ScreenToWorldPoint.html

Finally as the touch position moves you’ll want to draw new line segments. In your code you always set the first position in the array, and this is probably why you cannot see any lines.