This is not a question; it’s something I worked out just now, and it was a bit of a pain in the neck, so I thought I’d share.
What this actually does is draw a thin GUI.Box, but rotated, so that it fits neatly around the two endpoints. I’m using this to draw the track for a sliding widget, where the endpoints of the track are arbitrary (not necessarily axis-aligned). You could also use it to draw thick or thin lines between two points for other purposes. Just note that it’s not really drawing a line — it’s drawing a texture, just like GUI.Box does.
void DrawBoxAroundPoints(Vector2 p0, Vector2 p1, float height=6, float extraLength=0) {
// Draw a thin, rotated box around the line between the given points.
// Our approach is to rotate the GUI transformation matrix around the center
// of the line, and then draw an unrotated (horizontal) box at that point.
float width = (p1-p0).magnitude + extraLength;
Vector2 center = (p0 + p1) * 0.5f;
Rect horizontalRect = new Rect(center.x - width/2, center.y - height/2, width, height);
float angle = Mathf.Atan2(p1.y-p0.y, p1.x-p0.x) * Mathf.Rad2Deg;
Matrix4x4 savedMatrix = GUI.matrix;
Vector3 centerScreen = GUIUtility.GUIToScreenPoint(center);
GUI.matrix =
Matrix4x4.TRS(centerScreen, Quaternion.identity, Vector3.one)
* Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, angle), Vector3.one)
* Matrix4x4.TRS(-centerScreen, Quaternion.identity, Vector3.one)
* GUI.matrix;
GUI.Box(horizontalRect, "");
GUI.matrix = savedMatrix;
}
Also note that this works correctly even when your GUI matrix has already been scaled or translated (which is why we’re doing the extra steps to update GUI.matrix ourselves, rather than using GUIUtility.RotateAroundPivot). Hope this proves useful to somebody!
Cheers,
- Joe