![在此处输入图像描述](https://i.stack.imgur.com/936ZV.gif)
几个月前我做了非常相似的事情。可以使用LineRenderer和PolygonCollider2D来完成。您必须知道如何以新用户的身份阅读文档,因为它有很多您不知道的信息。
如何执行此操作的步骤:
1LineRenderer
.从代码中创建新的。
2 .Assign Material给新的Line Renderer,设置宽度和颜色。
3 .Get 中的点,PolygonCollider2D
其中返回点的数组PolygonCollider2D
。
4 .循环点并使用函数将每个点从本地空间转换为世界空间TransformPoint
..
5SetVertexCount
.将LineRenderer
的 设置Length
为点的 加 1。我们需要额外的 1 来关闭我们正在绘制的内容。
画线:
6 .最后,循环点并通过使用函数更改 LineRenderer 的位置来绘制线条SetPosition
。
LineRenderer.SetPosition(currentLoop, pointsArray[currentLoop]);
由于这是 2D,您可能需要修改 pointsArray 的 Z 轴以确保该对象显示在每个 GameObject 的前面。
7 . 通过从最后一个( pointsArray.Length
) 点位置到第一个(pointsArray[0]) 点绘制一条新线来关闭该线。
LineRenderer.SetPosition(pointsArray.Length, pointsArray[0]);
下面是一个可以完全做到这一点的函数。您也可以扩展它以支持其他 2D 对撞机。只需创建一个脚本并复制其中的代码即可。将附加了 PolygonCollider2D 的 Sprite 拖到 myGameObject 插槽,然后单击 Play。它将在该精灵上画线。
该highlightAroundCollider(pColider, Color.yellow, Color.red, 0.1f);
函数在调用它时为您提供选项,例如设置它的size
和color
。
using UnityEngine;
using System.Collections;
public class LineDrawerTest : MonoBehaviour
{
public GameObject myGameObject;
private PolygonCollider2D pColider;
protected void Start()
{
pColider = myGameObject.GetComponent<PolygonCollider2D>();
highlightAroundCollider(pColider, Color.yellow, Color.red, 0.1f);
}
void highlightAroundCollider(Component cpType, Color beginColor, Color endColor, float hightlightSize = 0.3f)
{
//1. Create new Line Renderer
LineRenderer lineRenderer = gameObject.GetComponent<LineRenderer>();
if (lineRenderer == null)
{
lineRenderer = cpType.gameObject.AddComponent<LineRenderer>();
}
//2. Assign Material to the new Line Renderer
lineRenderer.material = new Material(Shader.Find("Particles/Additive"));
float zPos = 10f;//Since this is 2D. Make sure it is in the front
if (cpType is PolygonCollider2D)
{
//3. Get the points from the PolygonCollider2D
Vector2[] pColiderPos = (cpType as PolygonCollider2D).points;
//Set color and width
lineRenderer.SetColors(beginColor, endColor);
lineRenderer.SetWidth(hightlightSize, hightlightSize);
//4. Convert local to world points
for (int i = 0; i < pColiderPos.Length; i++)
{
pColiderPos[i] = cpType.transform.TransformPoint(pColiderPos[i]);
}
//5. Set the SetVertexCount of the LineRenderer to the Length of the points
lineRenderer.SetVertexCount(pColiderPos.Length + 1);
for (int i = 0; i < pColiderPos.Length; i++)
{
//6. Draw the line
Vector3 finalLine = pColiderPos[i];
finalLine.z = zPos;
lineRenderer.SetPosition(i, finalLine);
//7. Check if this is the last loop. Now Close the Line drawn
if (i == (pColiderPos.Length - 1))
{
finalLine = pColiderPos[0];
finalLine.z = zPos;
lineRenderer.SetPosition(pColiderPos.Length, finalLine);
}
}
}
//Not Implemented. You can do this yourself
else if (cpType is BoxCollider2D)
{
}
}
void Update()
{
}
}