【Unity2D划线简单实现】

Unity2D划线

2D划线代码实现

// 2D划线
using UnityEngine;

public class GameObjectBrush : MonoBehaviour
{
    [SerializeField] private float width = 0.1f;
    [SerializeField] private Color color = Color.grey;

    private LineRenderer currentLR;
    private Vector2 previousPoint;

    private void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //线条渲染
            currentLR = new GameObject("LineRenderer").AddComponent<LineRenderer>();
            currentLR.material = new Material(Shader.Find("Sprites/Default")) { color = color };
            currentLR.widthMultiplier = width;
            currentLR.useWorldSpace = false;
            currentLR.positionCount = 1;
            currentLR.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))
            {
                //线条渲染
                currentLR.positionCount++;
                currentLR.SetPosition(currentLR.positionCount - 1, (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition));

                //碰撞器
                BoxCollider2D collider = new GameObject("BoxCollider2D").AddComponent<BoxCollider2D>();
                collider.transform.parent = currentLR.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 (currentLR.transform.childCount > 0)
            {
                currentLR.gameObject.AddComponent<Rigidbody2D>().useAutoMass = true;
            }
        }
    }
}

原文链接:
[1]: https://zhuanlan.zhihu.com/p/466894203?utm_campaign=&utm_medium=social&utm_oi=49424810115072&utm_psn=1568675188522328065&utm_source=qq

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值