Unity游戏开发——画出有物理效果的线
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(); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律