以下代码实现画线
public class Line : MonoBehaviour
{
// Start is called before the first frame update
public LineRenderer lineRenderer;
public EdgeCollider2D edgeCollider2D;
public Color color;
List points;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void updateLine(Vector2 mousePos)//更新新的点
{
if (points == null)
{
points = new List<Vector2>();
setPoint(mousePos);
return;
}
if (Vector2.Distance(points[points.Count-1], mousePos) > 0.1f)
{
setPoint(mousePos);
}
}
void setPoint(Vector2 newPoint)
{
points.Add(newPoint);
lineRenderer.positionCount = points.Count;
lineRenderer.SetPosition(points.Count - 1, newPoint);
if(points.Count>1)
edgeCollider2D.points = points.ToArray();
}
}
public class LineCreator : MonoBehaviour
{
// Start is called before the first frame update
public GameObject[] linePrefab;
private GameObject targetLine;
private int targetLineIndex;
Line activeLine;
void Start()
{
targetLine = linePrefab[0];
targetLineIndex = 0;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject lineGo = Instantiate(targetLine);
activeLine = lineGo.GetComponent<Line>();
}
if (Input.GetMouseButtonUp(0))
{
activeLine = null;
}
if (activeLine != null)
{
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
activeLine.updateLine(mousePos);
}
if (Input.GetMouseButtonDown(1))
{
ChangeTargetLine();
}
}
void ChangeTargetLine()
{
if (targetLine == null)
{
targetLine = linePrefab[0];
targetLineIndex = 0;
}
else if (targetLineIndex < linePrefab.Length - 1)
{
targetLine = linePrefab[++targetLineIndex];
}
else if (targetLineIndex == linePrefab.Length - 1)
{
targetLine = linePrefab[0];
targetLineIndex = 0;
}
}
}
改变sorting layer 没有用。