Map tool 구현4

ㅋㅋ·2022년 9월 15일
0

Custom Grid class

public class CustomGrid : MonoBehaviour
{
    ...

    public Dictionary<Vector2Int, MapObejct> Items = new Dictionary<Vector2Int, MapObejct>();
    
    ...

}

CustomGrid 클래스에 dictionary로 맵에 그려지는 오브젝트들을 관리할 수 있도록 구현

public bool Contains(Vector2Int cellPos)
{
    return 0 <= cellPos.x && cellPos.x < config.CellCount.x && 0 <= cellPos.y && cellPos.y < config.CellCount.y;
}

public bool IsItemExist(Vector2Int cellPos)
{
    return Items.ContainsKey(cellPos);
}

public MapObejct GetItem(Vector2Int cellPos)
{
    ...

    return Items[cellPos];
}

public MapObejct AddItem(Vector2Int cellPos, CustomGridPaletteItem paletteItem)
{
    ...

    var target = GameObject.Instantiate(paletteItem.targetObject, transform);
    target.transform.position = GetWorldPos(cellPos);
    var component = target.AddComponent<MapObejct>();
    component.id = paletteItem.id;
    component.cellPos = cellPos;

    Items.Add(cellPos, component);

    return component;
}

public void RemoveItem(Vector2Int cellPos)
{
    ...

    Items.Remove(cellPos);
}

tool window 클래스에서 마우스 이벤트가 발생한 위치에 대한 그리드 정보를 얻을 수 있도록

함수들을 구현


Tool window class

private void OnScencGUI(SceneView obj)
{
    ...
    {
        ...

        var cellPos = targetGrid.GetCellPos(hitPos);

        if (targetGrid.Contains(cellPos))
        {
            if (selectedEditToolMode == EditToolMode.Paint)
            {
                Paint(cellPos);
            }
            else if (selectedEditToolMode == EditToolMode.Erase)
            {
                Erase(cellPos);
            }
        }
    }
}

OnSceneGUI 이벤트 함수에서 마우스가 클릭된 위치에 모드에 따라

새로운 아이템을 그리거나 지우도록 구현


private void Paint(Vector2Int cellPos)
{
    ...

    if (targetGrid.IsItemExist(cellPos))
    {
        GameObject.DestroyImmediate(targetGrid.GetItem(cellPos).gameObject);
        targetGrid.RemoveItem(cellPos);
    }

    var target = targetGrid.AddItem(cellPos, selectedItem);

    Event.current.Use();
}

private void Erase(Vector2Int cellPos)
{
    if (targetGrid.IsItemExist(cellPos))
    {
        GameObject.DestroyImmediate(targetGrid.GetItem(cellPos).gameObject);
        targetGrid.RemoveItem(cellPos);

        Event.current.Use();
    }
}

Paint 함수에서는 그리드에 이미 아이템이 존재할 경우 삭제 후 새로운 아이템을 추가

Erase 함수에서는 아이템이 존재하는 경우만 삭제하도록 구현한다.

0개의 댓글