I’ve made a world to screen line drawing script based on:
http://wiki.unity3d.com/index.php?title=DrawLine
I’m using the legacy UI, because it doesnt require a canvas and is easier to create at runtime, i also mostly use these UI features for debugging.
Here is what i have so far:
public static Texture2D lineTex;
public static void DrawLine(Rect rect) { DrawLine(rect, GUI.contentColor, 1.0f); }
public static void DrawLine(Rect rect, Color color) { DrawLine(rect, color, 1.0f); }
public static void DrawLine(Rect rect, float width) { DrawLine(rect, GUI.contentColor, width); }
public static void DrawLine(Rect rect, Color color, float width) { DrawLine(new Vector3(rect.x, rect.y,0), new Vector3(rect.x + rect.width, rect.y + rect.height, 0), color, width); }
public static void DrawLine(Vector3 pointA, Vector3 pointB) { DrawLine(pointA, pointB, GUI.contentColor, 1.0f); }
public static void DrawLine(Vector3 pointA, Vector3 pointB, Color color) { DrawLine(pointA, pointB, color, 1.0f); }
public static void DrawLine(Vector3 pointA, Vector3 pointB, float width) { DrawLine(pointA, pointB, GUI.contentColor, width); }
public static void DrawLine(Vector3 pointA, Vector3 pointB, Color color, float width)
{
Vector3 pointAOnScreen = Camera.main.WorldToScreenPoint(pointA);
pointAOnScreen.y = Screen.height - pointAOnScreen.y;
Vector3 pointBOnScreen = Camera.main.WorldToScreenPoint(pointB);
pointBOnScreen.y = Screen.height - pointBOnScreen.y;
Matrix4x4 matrix = GUI.matrix;
if (!lineTex) { lineTex = new Texture2D(1, 1); }
Color savedColor = GUI.color;
GUI.color = color;
float angle = Vector3.Angle(pointBOnScreen - pointAOnScreen, Vector3.right);
if (pointAOnScreen.y > pointBOnScreen.y) { angle = -angle; }
GUIUtility.ScaleAroundPivot(new Vector3((pointBOnScreen - pointAOnScreen).magnitude, width), new Vector3(pointAOnScreen.x, pointAOnScreen.y + 0.5f));
GUIUtility.RotateAroundPivot(angle, pointAOnScreen);
GUI.DrawTexture(new Rect(pointAOnScreen.x, pointAOnScreen.y, 1, 1), lineTex);
GUI.matrix = matrix;
GUI.color = savedColor;
}
However, when i try drawing a line between two points, it works just fine until the camera moves.
The line starts to jitter.
The lines also appear behind the camera.
I wouldnt mind culling them if they are out of vision also.