Unity 实现画线火柴人核心画线功能
最近抖音上很火的小游戏,其中的核心划线功能。
[SerializeField] private float width = 0.1f;
[SerializeField] private Color color = Color.black;
private LineRenderer line;
private Vector2 previousPoint;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
//创建线条并渲染
line = new GameObject("LineRenderer").AddComponent<LineRenderer>();
line.material = new Material(Shader.Find("Sprites/Default")) { color = color };
line.useWorldSpace = false;
line.widthMultiplier = width;
line.positionCount = 1;
line.SetPosition(0, (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition));
//更新线条数据
previousPoint = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
else if (Input.GetMouseButton(0))
{
if (previousPoint != (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition))
{
//线条渲染更新
line.positionCount++;
line.SetPosition(line.positionCount - 1, (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition));
//增加碰撞器
BoxCollider2D collider = new GameObject("BoxCollider2D").AddComponent<BoxCollider2D>();
collider.transform.parent = line.transform;
Vector2 latestPoint = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
collider.transform.position = (previousPoint + latestPoint) * 0.5f;
float angle = Mathf.Atan2((latestPoint - previousPoint).y, (latestPoint - previousPoint).x) * Mathf.Rad2Deg;
collider.transform.eulerAngles = new Vector3(0, 0, angle);
collider.size = new Vector2(Vector2.Distance(latestPoint, previousPoint), width);
//更新数据
previousPoint = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
}
else if (Input.GetMouseButtonUp(0))
{
if (line.transform.childCount > 0)
{
//添加刚体
line.gameObject.AddComponent<Rigidbody2D>().useAutoMass = true;
}
}
}