- Home /
Drawing a straight line between two points with 2D UI
Here is pseudocode for what I am trying to accomplish in c#.
void DrawLine(){
points a,b
a = point1.position
b = mouse.position
while mouse down{
// Draw straight line between points a and b here.
}
if b != point2.position{
//Delete Line
}
}
When a UI button is pressed this method is called. Point a is the position of the sprite button that called the method, and b is the mouse position updated in real time. While the mouse is still being held down, How would I draw a straight line between those two points? and the last if statement checks if the second point of the line, b, has the same position of another sprite and if not then delete the line? How do i accomplish this with Unity's 2D UI tools.
Answer by girault-al · Nov 11, 2018 at 08:38 PM
There is no UI line renderer in Unity. You could make use of the Unity UI Extension to draw that in a canvas.
If you are fine drawing a 3d line on a 2d plane, you can use the LineRenderer instead: put it in a canvas, set useWorldSpace
to false, and alignment
to LineAlignment.TransformZ
and it will be aligned in your canvas plane. To make sure it stays in front of your canvas, you can use sortingOrder = 1
or move it along the Z axis. To add points, do positionCount++
then SetPosition()
.