用笔刷的形式实现地图编辑器

我们策划需要在方块地图中刷不同的单元格,正好之前对类似于魔兽编辑器的功能比较感兴趣,就用射线+物体生成的方式实现了下,实现效果截图如下:

清除效果:

实现代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class CreatMapUpdate : MonoBehaviour
{
    public GameObject[] objs;

    public Button[] btns;

    public int creatID = 0;

    public float length = 2.5f;
    public float width = 2.5f;

    public Dictionary<Vector2, GameObject> dic = new Dictionary<Vector2, GameObject>();

    // Start is called before the first frame update
    void Start()
    {       
        for (var _i = 0; _i < btns.Length; _i++)
        {
            var _j = _i;
            btns[_i].onClick.AddListener(delegate { Debug.LogError(_j); creatID = _j - 1; });
        }
    }

    // Update is called once per frame
    void Update()
    {
        
        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition/*+new Vector3(15,0,-15)*/);
            RaycastHit hit;
            //判断是否碰撞到物体
            bool isCollider = Physics.Raycast(ray, out hit) && hit.transform.tag == "TouchCreat";
            if (isCollider)
            {
                var _creatPos = new Vector2((int)(hit.point.x / length), (int)(hit.point.z / width));
                //Debug.Log(hit.point +"   "+_creatPos);

                GameObject.Find("指示球").transform.position = hit.point;
                //以0,0点为中心,将地图切割为n个小地图块

                if (dic.ContainsKey(_creatPos))
                {
                    var _obj = dic[_creatPos];
                    if (creatID == -1)
                    {
                        dic.Remove(_creatPos);
                        Destroy(_obj);
                    }
                    else if (_obj.name != objs[creatID].name)
                    {
                        Destroy(_obj);
                        _obj = CreatObj(objs[creatID]);
                        dic[_creatPos] = _obj;
                        _obj.transform.position = new Vector3(_creatPos.x * length, 0, _creatPos.y * length);
                        _obj.transform.SetParent(transform);
                    }
                }
                else if (creatID >= 0)
                {
                    var _obj = CreatObj(objs[creatID]);
                    dic.Add(_creatPos, _obj);
                    _obj.transform.localPosition= new Vector3(_creatPos.x * length, 0, _creatPos.y * length);
                    _obj.transform.SetParent(transform);
                    //Debug.Log(objs.Length + "  " + creatID);
                }
               
            }
        }
       
    }


    public GameObject CreatObj(GameObject _oo)
    {
        var _obj = GameObject.Instantiate(_oo) as GameObject;
        _obj.name = _oo.name;
        return _obj;
    }
}

工程资源下载地址:地图笔刷编辑器.unitypackage-C#文档类资源-CSDN文库

猜你喜欢

转载自blog.csdn.net/Tel17610887670/article/details/128578102
今日推荐