![](/img/trans.png)
[英]Draw line between two game objects using linerenderer and raycast
[英]How can I draw/display a text on each corner of two connected line of linerenderer?
using UnityEngine;
public class Square : MonoBehaviour
{
public LineRenderer lineRenderer;
private void Start()
{
if(lineRenderer == null)
{
lineRenderer = GetComponent<LineRenderer>();
lineRenderer.startWidth = 0.3f;
lineRenderer.endWidth = 0.3f;
}
// 0, 0, 0
// 5, 0, 0
// 5, -5, 0
// 0, -5, 0
Vector3[] positions = new Vector3[4] { new Vector3(0, 0, 0), new Vector3(5, 0, 0), new Vector3(5, -5, 0), new Vector3(0, -5, 0) };
DrawSquare(positions);
}
void DrawSquare(Vector3[] vertexPositions)
{
lineRenderer.positionCount = 4;
lineRenderer.SetPositions(vertexPositions);
}
}
结果是:
这是我想将显示文本绘制为连接两条用蓝色圆圈标记的线的角的示例:
每条连接两条线我想显示一条带有连接线坐标的文本,例如 0,0,0 或 0,5,0
解决方案:
using UnityEngine;
public class DrawLines : MonoBehaviour
{
public LineRenderer lineRenderer;
public string text;
private Vector3[] positions;
private void Start()
{
if (lineRenderer == null)
{
lineRenderer = GetComponent<LineRenderer>();
lineRenderer.startWidth = 0.3f;
lineRenderer.endWidth = 0.3f;
}
// 0, 0, 0
// 5, 0, 0
// 5, -5, 0
// 0, -5, 0
positions = new Vector3[4] { new Vector3(0, 0, 0), new Vector3(5, 0, 0),
new Vector3(5, -5, 0), new Vector3(0, -5, 0)};
DrawLine(positions, Color.red, 0.2f);
}
void DrawLine(Vector3[] positions, Color color, float duration = 0.2f)
{
GameObject myLine = new GameObject();
myLine.transform.position = positions[0];
myLine.AddComponent<LineRenderer>();
LineRenderer lr = myLine.GetComponent<LineRenderer>();
lr.positionCount = positions.Length;
lr.startColor = color;
lr.endColor = color;
lr.startWidth = 0.1f;
lr.endWidth = 0.1f;
lr.useWorldSpace = false;
lr.SetPositions(positions);
}
void DrawText()
{
for (int i = 0; i < positions.Length; i++)
{
var pos = Camera.main.WorldToScreenPoint(positions[i]);
text = positions[i].ToString();
var textSize = GUI.skin.label.CalcSize(new GUIContent(text));
GUI.contentColor = Color.red;
GUI.Label(new Rect(pos.x, Screen.height - pos.y, textSize.x, textSize.y), text);
}
}
private void OnGUI()
{
if (positions != null)
{
if (positions.Length > 0)
{
DrawText();
}
}
}
}
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.