- Home /
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 :(
you have set only one points position you must have to do lineRenderer.SetPosition(1, otherPosition);
Answer by Graham-Dunnett · Feb 19, 2012 at 06:36 PM
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.
Thank you but I have tried this. and making the correct 2D point from a 3D point does seem a bit impossible.
As Graham states you'd use ScreenToWorldPoint, then you can pass Touch.position into it (keep in $$anonymous$$d that's a Vector2 and ScreenToWorldPoint takes Vector3). Depending on the functionality of the line you could use a raycast from that Touch.position, you'd have an invisible plane to always make the ray bounce and give back data.
Your answer
Follow this Question
Related Questions
Drawing lines between two touch positions? 4 Answers
Small question about converting from Android to iOS 1 Answer
Delta touch trembling 0 Answers
Unity Event Trigger iOS 1 Answer