using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Starry { public class DrawLine : MonoBehaviour { public Material line; public bool gravity; public Color lineColor = Color.white; private List<GameObject> lineList = new List<GameObject>(); private List<Vector2> pointList = new List<Vector2>(); private GameObject currentLine; private LineRenderer currentLineRenderer; private bool stopHolding; private static readonly int EmissionColor = Shader.PropertyToID("_EmissionColor"); private void Update() { if (Input.GetMouseButtonDown(0)) { pointList.Clear(); CreateLine(); } if (Input.GetMouseButton(0)) { Vector2 item = Camera.main.ScreenToWorldPoint(Input.mousePosition); if (!pointList.Contains(item)) { pointList.Add(item); currentLineRenderer.positionCount = pointList.Count; currentLineRenderer.SetPosition(pointList.Count - 1, pointList.Last()); if (pointList.Count >= 2) { Vector2 vector1 = pointList[pointList.Count - 2]; Vector2 vector2 = pointList[pointList.Count - 1]; GameObject currentCollierObject = new GameObject("Collider"); currentCollierObject.transform.position = (vector1 + vector2) / 2f; currentCollierObject.transform.right = (vector2 - vector1).normalized; currentCollierObject.transform.parent = currentLine.transform; BoxCollider2D currentBoxCollider2D = currentCollierObject.AddComponent<BoxCollider2D>(); currentBoxCollider2D.size = new Vector3((vector2 - vector1).magnitude, 0.1f, 0.1f); currentBoxCollider2D.enabled = false; } } } if (Input.GetMouseButtonUp(0)) { if (currentLine.transform.childCount > 0) { for (int i = 0; i < currentLine.transform.childCount; i++) { currentLine.transform.GetChild(i).GetComponent<BoxCollider2D>().enabled = true; } lineList.Add(currentLine); if (gravity) { currentLine.AddComponent<Rigidbody2D>().useAutoMass = true; } } else { Destroy(currentLine); } } } private void CreateLine() { currentLine = new GameObject("Line"); currentLineRenderer = currentLine.AddComponent<LineRenderer>(); currentLineRenderer.material = line; currentLineRenderer.material.EnableKeyword("_EMISSION"); currentLineRenderer.material.SetColor(EmissionColor, this.lineColor); currentLineRenderer.positionCount = 0; currentLineRenderer.startWidth = 0.1f; currentLineRenderer.endWidth = 0.1f; currentLineRenderer.startColor = lineColor; currentLineRenderer.endColor = lineColor; currentLineRenderer.useWorldSpace = false; } public void ClearAll() { foreach (var obj in lineList) { Destroy(obj); } lineList.Clear(); } } }
标签:游戏,currentLine,画出,transform,private,Unity,currentCollierObject,currentLineRender From: https://www.cnblogs.com/ld839216579/p/17010024.html