LoadLevel.cs 12.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class LoadLevel : MonoBehaviour
{
    public string levelName;    // Name of the level in the Resources/Levels folder
                                // There should be a .png for the tile map of the level and a text file detailing which prefabs
                                // correlate to which RGB value
                                // The text file lists the path of the prefab to be used and the RGB value assigned to that prefab

    public Material mat;

    private GameObject tilesParent;
    private bool updated = false;

    void Start()
    {
        create();
    }

    void Update()
    {
        if (!updated)
            setMaterials();
    }

    public void create()
    {
        clear();

        Vector3 scale = transform.localScale;   // Store scale to rescale when finished creating map
        transform.localScale = Vector3.one;     // Set scale to 1 so new objects get scaled down

        Texture2D level = pathToTex(levelName); // Image of level
        Color32[] pixels = level.GetPixels32(); // Pixels of the image
        World.setup(level.width, level.height);

        Dictionary<byte, Dictionary<byte, Dictionary<byte, GameObject[]>>> rgbDic = new Dictionary<byte, Dictionary<byte, Dictionary<byte, GameObject[]>>>();   // RGB mapping of prefabs
        Dictionary<byte, GameObject> aDic = new Dictionary<byte, GameObject>();                                                                                 // Alpha mapping of prefabs
        pathToTiles(levelName, out rgbDic, out aDic);

        tilesParent = new GameObject();
        tilesParent.transform.parent = transform;
        tilesParent.name = "Tiles";

        for (int x = 0; x < level.width; x++)
        {
            byte r, g, b, a;
            int pos;
            GameObject pref, border;
            for (int y = 0; y < level.height; y++)
            {
                pos = x + (y * level.width);

                a = pixels[pos].a;
                if (a > 0)  // Dont create objects for enpty pixels
                {
                    r = pixels[pos].r;
                    g = pixels[pos].g;
                    b = pixels[pos].b;
                    pref = rgbDic[r][g][b][0];
                    border = rgbDic[r][g][b][1];

                    GameObject go = (GameObject)Instantiate(pref, new Vector3(x, y), Quaternion.identity);
                    go.transform.parent = tilesParent.transform;
                    go.name = "(" + x + "," + y + ")";

                    // Add borders if same tiles are not next to it and it has a border
                    if(border != null)
                    {
                        int xOffset, yOffset;
                        int posN;           // Pos of neighbor
                        Color32 colorN;     // Color32 of neighbor
                        for (int i = 0; i < 4; i++)
                        {
                            // DOWN
                            if(i == 0)
                            {
                                xOffset = 0;
                                yOffset = -1;
                            }
                            // RIGHT
                            else if (i == 1)
                            {
                                xOffset = 1;
                                yOffset = 0;
                            }
                            // UP
                            else if (i == 2)
                            {
                                xOffset = 0;
                                yOffset = 1;
                            }
                            // LEFT
                            else // (i == 3)
                            {
                                xOffset = -1;
                                yOffset = 0;
                            }
                            if (x + xOffset >= 0 && x + xOffset < level.width && y + yOffset >= 0 && y + yOffset < level.height)
                            {
                                posN = (x + xOffset) + ((y + yOffset) * level.width);
                                colorN = pixels[posN];
                                if (r != colorN.r || g != colorN.g || b != colorN.b)
                                {
                                    GameObject borderGO = (GameObject)Instantiate(border, new Vector3(x + .5f, y + .5f), Quaternion.Euler(0, 0, (90 * i)));
                                    borderGO.transform.parent = go.transform;
                                    borderGO.name = "Border " + i;
                                }
                            }else
                            {
                                GameObject borderGO = (GameObject)Instantiate(border, new Vector3(x + .5f, y + .5f), Quaternion.Euler(0, 0, (90 * i)));
                                borderGO.transform.parent = go.transform;
                                //borderGO.transform.position = Vector3.zero;
                                borderGO.name = "Border " + i;
                            }
                        }
                    }

                    //world.set(x, y, go.GetComponentInChildren<Tile>()); // Add tile to world
                    Tile t = go.GetComponentInChildren<Tile>();
                    if (t == null)
                        Debug.LogError(pref.name + " has no Tile!");
                    t.x = x;
                    t.y = y;
                    World.set(x, y, t);

                    if (aDic.TryGetValue(a, out pref))
                    {
                        GameObject goA = (GameObject)Instantiate(pref, new Vector3(x, y), Quaternion.identity);
                        SpriteRenderer sr = goA.GetComponent<SpriteRenderer>();
                        if(sr != null)
                        {
                            sr.sortingOrder = 100;
                        }
                        goA.transform.parent = transform;
                        go.name = pref.name;
                    }
                }
            }
        }
        transform.localScale = scale;   // Restore scale

        fixCamera(World.Width, World.Height);
    }

    public void clear()
    {
        if (tilesParent != null)
        {
            /*Transform[] children = tilesParent.GetComponentsInChildren<Transform>();
            foreach (Transform trans in children)
            {
                if (trans != null)
                    DestroyImmediate(trans.gameObject);
            }*/
            DestroyImmediate(tilesParent);
        }
    }

    // Returns Texture2D from the given filename
    private Texture2D pathToTex(string path)
    {
        Texture2D tex;
        path = "Levels/" + path;
        try
        {
            tex = Resources.Load<Texture2D>(path);
        }
        catch (System.Exception)
        {
            Debug.LogError(path + " Not Found!");
            throw;
        }
        return tex;
    }

    // Returns a Dictionary of Dictionaries of Dictionaries of GameObject using the key r(ed),g(reen),b(lue)
    // and a Dictionary of GameObjects using the key a(lpha) from the Resources/Levels text file
    // The file lists the path of the prefab to be used and the RGB or alpha value assigned to that prefab
    // A line with just ":" seperates the RGB mapping from the alpha mapping
    //
    // Example mapping Tiles/Tile_0 to full red:
    // Tiles/Tile_0
    // 255
    // 0
    // 0
    //
    // Example mapping Enemies/Enemy_0 to alpha value 50:
    // Tiles/Tile_0
    // 50
    private void pathToTiles(string path,   out Dictionary<byte, Dictionary<byte, Dictionary<byte, GameObject[]>>> rgbDic /*Dictionary for RGB lookup*/,
                                            out Dictionary<byte, GameObject> aDic   /*Dictionary for alpha lookup*/)
    {
        rgbDic = new Dictionary<byte, Dictionary<byte, Dictionary<byte, GameObject[]>>>();
        aDic = new Dictionary<byte, GameObject>();

        StreamReader sr;
        path = Application.dataPath + "/Resources/Levels/" + path + ".txt";

        try
        {
            GameObject go, border;
            byte r, g, b;
            string line;
            bool doingAlphas = false;

            sr = new StreamReader(path);

            while (!sr.EndOfStream) // Read values until EOS
            {
                line = sr.ReadLine();
                if (line == ":")
                {
                    doingAlphas = true;
                    line = sr.ReadLine();
                }

                go = AssetDatabase.LoadAssetAtPath<GameObject>(line);  // Load GameObject
                line = sr.ReadLine();

                if (!char.IsDigit(line[0]))  // Has a border
                {
                    border = AssetDatabase.LoadAssetAtPath<GameObject>(line);
                    line = sr.ReadLine();
                }
                else
                    border = null;

                if (!doingAlphas)    // Reading RGB values
                {
                    byte.TryParse(line, out r); // Read red value
                    line = sr.ReadLine();
                    byte.TryParse(line, out g); // Read green value
                    line = sr.ReadLine();
                    byte.TryParse(line, out b); // Read blue value

                    //Debug.Log(r + ", " + g + ", " + b + " | " + go.name);

                    Dictionary<byte, Dictionary<byte, GameObject[]>> dicR;
                    if (rgbDic.TryGetValue(r, out dicR))   // Lookup red key in dic
                    {
                        Dictionary<byte, GameObject[]> dicG;
                        if (dicR.TryGetValue(g, out dicG))  // Lookup green key in dicR
                        {
                            GameObject[] goB;
                            if (dicG.TryGetValue(b, out goB))   // Lookup blue key in dicB
                            {
                                Debug.LogWarning(r + ", " + g + ", " + b + " Already Used With: " + goB[0].name);
                            }
                            else
                            {
                                // Create entry for b, go
                                dicG.Add(b, new GameObject[] { go, border });
                            }
                        }
                        else
                        {
                            // Create entry for g, b, go
                            dicG = new Dictionary<byte, GameObject[]>();
                            dicG.Add(b, new GameObject[] { go, border });
                            dicR.Add(g, dicG);
                        }
                    }
                    else
                    {
                        // Create entry for r, g, b, go
                        dicR = new Dictionary<byte, Dictionary<byte, GameObject[]>>();
                        Dictionary<byte, GameObject[]> dicG = new Dictionary<byte, GameObject[]>();
                        dicG.Add(b, new GameObject[] { go, border });
                        dicR.Add(g, dicG);
                        rgbDic.Add(r, dicR);
                    }
                }else    // Reading alpha values
                {
                    byte.TryParse(line, out r); // Read alpha value (store in r because it wont be used any more)

                    //Debug.Log(r + " | " + go.name);

                    GameObject goA;
                    if(aDic.TryGetValue(r, out goA))
                    {
                        Debug.LogWarning(r + " Already Used With: " + goA.name);
                    }else
                    {
                        // Create entry for a, go
                        aDic.Add(r, go);
                    }
                }
            }
        }
        catch (System.Exception)
        {
            throw;
        }
        sr.Close();
    }

    // Move and resize main camera to show entire level
    private void fixCamera(int width, int height)
    {
        float x = (width / 2) * transform.localScale.x;
        float y = (height / 2) * transform.localScale.y;
        Camera cam = Camera.main;
        cam.orthographicSize = Mathf.Max(x ,y);
        cam.transform.position = new Vector3(x, y, -10);
    }

    private void setMaterials()
    {
        if (mat != null)
        {
            Renderer[] renderers = tilesParent.GetComponentsInChildren<Renderer>();
            foreach (Renderer rend in renderers)
            {
                rend.material = mat;
            }
        }
    }
}

[CustomEditor(typeof(LoadLevel))]
public class LoadLevelEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        if (GUILayout.Button("Create"))
        {
            ((LoadLevel)target).create();
        }

        if (GUILayout.Button("Clear"))
        {
            ((LoadLevel)target).clear();
        }
    }
}