Scroll View 동적생성

Unity/수업내용 2019. 5. 28. 09:48


UGUI를 이용, json 파일을 통해서 scroll view의 항목들을 동적으로 생성해보았다.



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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.U2D;
 
public class TestUGUI : MonoBehaviour
{
    public SpriteAtlas atlas;
    public RectTransform contents;
    public MissionListItem listItemPrefab;
    private DataManager dm;
 
    void Start()
    {
 
        this.dm = DataManager.GetInstance();
        dm.LoadData<mission_data>("Data/mission_data");
        dm.LoadData<reward_data>("Data/reward_data");
 
        var mission0 = dm.GetData<mission_data>(0);
        Debug.LogFormat(mission0.sprite_name);
 
        dm.GetCount();
        this.CreateListItem();
    }
 
    private void CreateListItem()
    {
        for (int i = 0; i<5; i++)
        {
            var data = this.dm.GetData<mission_data>(i);
            var listItemGo = Instantiate(this.listItemPrefab);
 
            var script = listItemGo.GetComponent<MissionListItem>();
            script.Init(data.id, this.dm.GetData<reward_data>(data.reward_id).sprite_name, data.sprite_name, data.reward_val, data.mission_name, data.goal_val,
                    this.dm.GetData<reward_data>(data.reward_id).hex_color);
        }
    }
}
 
cs


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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.U2D;
 
public class MissionListItem : MonoBehaviour
{
    public int id;
    public Image rewardIcon, Thumb;
    public Image[] Stars;
    public Text rewardText, MissionName;
    public GameObject bg;
    public Button claim;
 
    public void Init(int id, string rewardIcon, string Thumb, int rewardText, string MissionName, int goalValue, string hex_color)
    {
        this.Claim();
        this.gameObject.transform.SetParent(GameObject.Find("Contents").transform);
        var atlas = GameObject.FindObjectOfType<TestUGUI>().atlas;
        this.bg.SetActive(false);
        this.id = id;
        this.rewardIcon.sprite = atlas.GetSprite(rewardIcon);
        this.Thumb.sprite = atlas.GetSprite(Thumb);
        this.rewardText.text = rewardText.ToString();
        Color color;
        ColorUtility.TryParseHtmlString(hex_color, out color);
        this.rewardText.color = color;
        this.MissionName.text = string.Format(MissionName,goalValue.ToString());
    }
 
    private void Claim()
    {
        this.claim.onClick.AddListener(() =>
        {
            var dm = DataManager.GetInstance();
            Debug.LogFormat("id : {0}, reward : {1}, reward_Value : {2}"this.id, this.rewardIcon.name, this.rewardText.text);
        });
    }
}
 
cs




1
2
3
4
5
6
7
8
9
10
 
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class RawData
{
    public int id;
}
 
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class mission_data : RawData
{
    public string sprite_name;
    public string mission_name;
    public int goal_val;
    public int reward_id;
    public int reward_val;
}
 
cs

1
2
3
4
5
6
7
8
9
10
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class reward_data : RawData
{
    public string sprite_name;
    public string hex_color;
}
 
cs


:

UGUI를 이용해 Scroll View UI 만들기

Unity/수업내용 2019. 5. 24. 19:08



오늘은 NGUI, UGUI의 기본적인 것을 배우고 UGUI를 이용하여 Scroll View 기능이 있는 UI를 만들어 보았다.

만든건 Mission(Quest) UI인데, Claim은 버튼으로 총 3가지가 가능하게 만들었다. (완료가능, 완료, 완료불가능)

나름 재밌었다. UI 공부 좀 많이 해야할 것 같다.


Component : Content Size fitter, Vertical Layout Group, Mask, Scroll Rect


하면서 배운 것 : Sprite Atlas, Atlas, UnityEngine.U2D(namespace)

:

A* Algorithm 좋은 영상

Algorithm/풀고있는 문제 2019. 5. 23. 11:22

https://www.youtube.com/watch?v=KNXfSOx4eEE


A* Pathfinding Tutorial - (CodeCompile)

이해하기 쉽게 되어있다.


https://www.youtube.com/watch?v=T8mgXpW1_vc


A* pathfinding for beginners implementation (theory) - (Kyle Stone)

6:40~7:10에 이해되지 않았던 G값 비교 부모 변환에 대해 잘 설명되어있다.

또한 손으로 하나하나 작성하여 보기좋다.

'Algorithm > 풀고있는 문제' 카테고리의 다른 글

A* Algorithm Simulation  (0) 2019.05.22
A* Algorithm 구현  (0) 2019.05.21
A* Algorithm 4방향/8방향 탐색  (0) 2019.05.20
A* Algorithm 진행중  (0) 2019.05.17
:

A* Algorithm Simulation

Algorithm/풀고있는 문제 2019. 5. 22. 19:16



다른 점 : OpenList를 Reset하지 않고, 누적하여 쌓는다.


icomparable

orderby

lambda




1) 현재노드의 인접노드 중에 오픈리스트에 없던 노드들의 부모를 현재 노드로 설정

2) 현재노드의 인접노드 중에 오픈리스트에 있던 노드가

   현재노드보다 g값이 작으면 오픈리스트에 없던 노드들의 부모를 그 노드로 설정

3) openlist에서 f값이 가장 작은 노드를 다음 current node로 설정



'Algorithm > 풀고있는 문제' 카테고리의 다른 글

A* Algorithm 좋은 영상  (0) 2019.05.23
A* Algorithm 구현  (0) 2019.05.21
A* Algorithm 4방향/8방향 탐색  (0) 2019.05.20
A* Algorithm 진행중  (0) 2019.05.17
:

A* Algorithm 구현

Algorithm/풀고있는 문제 2019. 5. 21. 17:14

A* 알고리즘

4방향과 8방향을 구현했다.

8방향에서는 다음 노드로 이동하는 경우 옆에 벽이 있으면 대각선으로 이동 못하게 구현했다.

이는 사각형이 통으로 움직인다고 가정했을 때, 옆에 벽이 있으면 사각형이 손실되기 때문이다.


근데 4방향 이동시에 문제점이 있는데, (0,3)노드를 지나고 (0,4)가 되는 순간부터 우측에 있는 노드를 인식하지 못한다.

(4,4)에서는 우측의 노드를 인식하고 마더노드 설정 후 이동을 하는데,

아무리 코드를 보고 고민을 해봐도 뭐가 문제인지 모르겠다.

문제점 해결 되면 추가로 포스팅해야겠다.




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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.UI;
 
public class Test0517 : MonoBehaviour
{
    public int row, col;
    public int startX, startY;
    public int targetX, targetY;
    public Button btn;
    public Button btn2;
    public GameObject character;
 
    private GameObject[] tilePrefabs;
    private GameObject[,] tiles;
    private GameObject motherNode;
    private GameObject startNode;
    private GameObject targetNode;
    private List<GameObject> listTile;
    private List<GameObject> openList;
    private List<GameObject> closeList;
    private List<GameObject> motherNodes;
    private List<GameObject> minList;
 
    private Vector2[,] coordinate;
 
    void Start()
    {
        this.minList = new List<GameObject>();
        this.motherNodes = new List<GameObject>();
        this.openList = new List<GameObject>();
        this.closeList = new List<GameObject>();
        this.tilePrefabs = Resources.LoadAll<GameObject>("Tiles");
        this.coordinate = new Vector2[this.row, this.col];
        this.tiles = new GameObject[this.row, this.col];
        this.listTile = new List<GameObject>();
 
        this.SetCorrdinate();
        this.CreateTiles();
        this.SetMotherNode(this.tiles[startX, startY]);
        this.SetOpenList();
        this.OrderByList();
        this.character.transform.position = this.motherNode.transform.position;
 
 
        this.btn.onClick.AddListener(() =>
        {
            if (closeList.LastOrDefault() == this.targetNode)
            {
                Debug.Log("목표 위치에 도달했습니다.");
            }
            else
            {
                this.SetOpenList();
                this.OrderByList();
                this.closeList.Add(this.openList.FirstOrDefault());
                this.ResetOpenList();
                if (this.CheckWall(this.openList.FirstOrDefault()))
                {
                    this.SetMotherNode(openList.FirstOrDefault());
                }
                else
                {
                    this.SetMotherNode(openList[1]);
                }
                this.openList.Clear();
                this.MoveCharacter();
            }
        });
 
        this.btn2.onClick.AddListener(() =>
        {
            if (closeList.LastOrDefault() == this.targetNode)
            {
                Debug.Log("목표 위치에 도달했습니다.");
            }
            else
            {
                bool tf = false;
                foreach (var nodes in this.minList)
                {
                    var list = this.minList.OrderBy(x => x.GetComponent<TestTile>().f);
                    if (nodes.GetComponent<TestTile>().vec2 == this.targetNode.GetComponent<TestTile>().vec2 && nodes.GetComponent<TestTile>().f == list.FirstOrDefault().GetComponent<TestTile>().f)
                    {
                        this.SetMotherNode(this.targetNode);
                        this.motherNode = this.targetNode;
                        this.motherNodes.Add(this.targetNode);
                        tf = true;
                        break;
                    }
                    tf = false;
                }
                if(tf == false)
                {
                    var orderList = this.minList.OrderBy(x => x.GetComponent<TestTile>().f).ToList();
                    this.closeList.Add(orderList.FirstOrDefault());
                    this.ResetOpenList();
                    this.SetMotherNode(orderList.FirstOrDefault());
                    this.openList.Clear();
                    this.minList.Clear();
                    this.MoveCharacter();
 
                    this.SetOpenList();
                    this.OrderByList();
                    foreach (var item in this.minList)
                    {
                        Debug.LogFormat("<color=blue>minList item : {0} </color>", item.GetComponent<TestTile>().vec2);
                    }
                }
            }
        });
    }
 
    #region 타일 검사 및 캐릭터 이동
    private bool CheckWall(GameObject node)
    {
        var checkNode = node;
        var x = checkNode.GetComponent<TestTile>().x;
        var y = checkNode.GetComponent<TestTile>().y;
 
        Debug.LogFormat("checkNode : {0}.{1}", x, y);
 
        if(this.motherNode.GetComponent<TestTile>().x < x)
        {
            //타겟의 x-1 / y-1 검사
            var targetNode1 = this.tiles[x - 1, y];
            var targetNode2 = this.tiles[x, y - 1];
            if(targetNode1.GetComponent<TestTile>().tileType == 1 || targetNode2.GetComponent<TestTile>().tileType == 1)
            {
                return false;
            }
        }
        else if(this.motherNode.GetComponent<TestTile>().x > x)
        { //4,3 -> 3,4  3,3 4,4
            //타겟의 x+1 / y+1 검사
            var targetNode1 = this.tiles[x + 1, y];
            var targetNode2 = this.tiles[x, y + 1];
            var targetNode3 = this.tiles[x, y - 1];
            if(targetNode1.GetComponent<TestTile>().tileType == 1 || targetNode2.GetComponent<TestTile>().tileType == 1 || targetNode3.GetComponent<TestTile>().tileType == 1)
            {
                return false;
            }
        }
        return true;
    }
 
    private void MoveCharacter()
    {
        var anim = this.character.GetComponentInChildren<Animation>();
        anim.Play("run@loop");
        StartCoroutine(this.MoveCharacterImpl());
    }
 
    private IEnumerator MoveCharacterImpl()
    {
        var anim = this.character.GetComponentInChildren<Animation>();
        var dir = (this.motherNode.transform.position - this.character.transform.position).normalized;
        
        while(true)
        {
            var dis = Vector3.Distance(this.character.transform.position, this.motherNode.transform.position);
            this.character.transform.position += (dir * 0.1f);
            yield return null;
            if(dis <= 0.1f)
            {
                this.character.transform.position = this.motherNode.transform.position;
                anim.Play("idle@loop");
                break;
            }
        }
    }
 
    #endregion
 
    #region OrderBy
 
    private void OrderByList()
    {
        var list = this.openList.OrderBy(x => x.GetComponent<TestTile>().f).ToList();
        this.openList = list;
        this.OrderByMin();
    }
 
    private void OrderByMin()
    {
        var list = this.openList.OrderBy(x => x.GetComponent<TestTile>().g).ToList();
        int index = 0;
        foreach (var tile in list)
        {
            Debug.LogFormat("{0} vs {1}", tile.GetComponent<TestTile>().g, list.FirstOrDefault().GetComponent<TestTile>().g);
            if (tile.GetComponent<TestTile>().g == list.FirstOrDefault().GetComponent<TestTile>().g && tile != this.motherNode)
            {
                this.minList.Add(list[index]);
            }
            index++;
        }
    }
 
    #endregion
 
    #region OpenList Set & Reset
    private void SetOpenList()
    {
        var motherX = this.motherNode.GetComponent<TestTile>().x - 1;
        var motherY = this.motherNode.GetComponent<TestTile>().y - 1;
        var maxX = this.motherNode.GetComponent<TestTile>().x + 1;
        var maxY = this.motherNode.GetComponent<TestTile>().y + 1;
        if (motherX < 0)
        {
            motherX = 0;
        }
        if (motherY < 0)
        {
            motherY = 0;
        }
 
        for (int i = motherX; i <= maxX; i++)
        {
            for (int j = motherY; j <= maxY; j++)
            {
                if (this.tiles[i, j].GetComponent<TestTile>().tileType == 0)
                {
                    this.openList.Add(this.tiles[i, j]);
                    this.SetG(this.tiles[i, j]);
                    this.SetH(this.tiles[i, j]);
                    this.SetF(this.tiles[i, j]);
                    var sprite = this.tiles[i, j].GetComponentInChildren<SpriteRenderer>();
                    sprite.color = Color.cyan;
                }
            }
        }
        this.TurnArrow();
    }
 
    private void ResetOpenList()
    {
        foreach (var tile in this.openList)
        {
            var sprite = tile.GetComponentInChildren<SpriteRenderer>();
            sprite.color = Color.white;
        }
        this.SetFalseArrow();
        this.SetFalseValue();
    }
    #endregion
 
    #region MotherNode Setting
    private void SetMotherNode(GameObject mother)
    {
        this.motherNode = mother;
        this.motherNodes.Add(this.motherNode);
        this.motherNode.GetComponent<TestTile>().tileType = 2;
        Debug.LogFormat("Mother node : {0}"this.motherNode.GetComponent<TestTile>().vec2);
        var sprite = this.motherNode.GetComponentInChildren<SpriteRenderer>();
        sprite.color = Color.gray;
    }
    #endregion
    
    #region Arrow, FGH Value, Coordinate
    private void TurnArrow()
    {
        foreach (var tile in this.openList)
        {
            var script = tile.GetComponent<TestTile>();
            var xPos = this.motherNode.transform.position.x - script.Arrow.transform.position.x;
            var yPos = this.motherNode.transform.position.y - script.Arrow.transform.position.y;
            var rad = Mathf.Atan2(yPos, xPos) * Mathf.Rad2Deg;
            script.Arrow.transform.rotation = Quaternion.Euler(new Vector3(00, rad + 270));
 
            script.Arrow.SetActive(true);
        }
    }
 
    private void SetFalseArrow()
    {
        foreach (var tile in this.openList)
        {
            var script = tile.GetComponent<TestTile>();
            script.Arrow.SetActive(false);
        }
    }
 
    private void SetFalseValue()
    {
        foreach (var tile in this.openList)
        {
            var script = tile.GetComponent<TestTile>();
            script.textF.text = "F";
            script.textG.text = "G";
            script.textH.text = "H";
        }
    }
 
    private void SetCorrdinate()
    {
        for (int i = 0; i < this.row; i++)
        {
            for (int j = 0; j < this.col; j++)
            {
                this.coordinate[i, j] = new Vector2(i, j);
            }
        }
    }
 
    private void SetF(GameObject tile)
    {
        var tileScript = tile.GetComponent<TestTile>();
        tileScript.f = tileScript.g + tileScript.h;
        tileScript.textF.text = tileScript.f.ToString("f0");
    }
 
    private void SetG(GameObject tile)
    {
        var tileScript = tile.GetComponent<TestTile>();
        var targetScript = this.targetNode.GetComponent<TestTile>();
        var dis = (Vector2.Distance(tile.transform.position, this.motherNode.transform.position)) * 10;
        tileScript.textG.text = dis.ToString("f0");
        tileScript.g = dis;
    }
 
    private void SetH(GameObject tile)
    {
        var tileScript = tile.GetComponent<TestTile>();
        var targetScript = this.targetNode.GetComponent<TestTile>();
        var dis = (Vector2.Distance(tile.transform.position, this.targetNode.transform.position)) * 10;
        tileScript.textH.text = dis.ToString("f0");
        tileScript.h = dis;
    }
    #endregion
 
    #region CreateTiles
    private void CreateTiles()
    {
 
        for (int i = 0; i < this.row; i++)
        {
            for (int j = 0; j < this.col; j++)
            {
                var screenPos = Camera.main.ScreenToWorldPoint(new Vector2((j * 100+ 400, (i * -100+ 550));
                screenPos.z = 0;
                if (i == this.startX && j == this.startY)
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[1]);
                    this.tiles[i, j] = tile;
                    this.startNode = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.vec2 = this.coordinate[i, j];
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
                else if (i == this.targetX && j == this.targetY)
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[2]);
                    this.tiles[i, j] = tile;
                    this.targetNode = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.vec2 = this.coordinate[i, j];
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
                else if ((i >= 1 && i < 4&& j == 3)
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[0]);
                    this.tiles[i, j] = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.tileType = 1;
                    script.vec2 = this.coordinate[i, j];
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
                else
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[3]);
                    this.tiles[i, j] = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.vec2 = this.coordinate[i, j];
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
            }
        }
    }
    #endregion
}
 
cs


'Algorithm > 풀고있는 문제' 카테고리의 다른 글

A* Algorithm 좋은 영상  (0) 2019.05.23
A* Algorithm Simulation  (0) 2019.05.22
A* Algorithm 4방향/8방향 탐색  (0) 2019.05.20
A* Algorithm 진행중  (0) 2019.05.17
:

A* Algorithm 4방향/8방향 탐색

Algorithm/풀고있는 문제 2019. 5. 20. 18:44



4방향은 고장났다...



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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using UnityEngine.UI;
 
public class Test0517 : MonoBehaviour
{
    public int row, col;
    public int startX, startY;
    public int targetX, targetY;
    public Button btn;
    public Button btn2;
 
    private GameObject[] tilePrefabs;
    private GameObject[,] tiles;
    private GameObject motherNode;
    private GameObject startNode;
    private GameObject targetNode;
    private List<GameObject> listTile;
    private List<GameObject> openList;
    private List<GameObject> closeList;
    private List<GameObject> motherNodes;
    private List<GameObject> minList;
    private float moveCost;
 
    private Vector2[,] coordinate;
 
    void Start()
    {
        this.minList = new List<GameObject>();
        this.motherNodes = new List<GameObject>();
        this.openList = new List<GameObject>();
        this.closeList = new List<GameObject>();
        this.tilePrefabs = Resources.LoadAll<GameObject>("Tiles");
        this.coordinate = new Vector2[this.row, this.col];
        this.tiles = new GameObject[this.row, this.col];
        this.listTile = new List<GameObject>();
 
        this.SetCorrdinate();
        this.CreateTiles();
        this.SetMotherNode(this.tiles[startX, startY]);
        this.SetOpenList();
 
        this.btn.onClick.AddListener(() =>
        {
            if (closeList.LastOrDefault() == this.targetNode)
            {
                Debug.Log("목표 위치에 도달했습니다.");
 
                foreach (var a in this.motherNodes)
                {
                    Debug.LogFormat("<color=red>{0}</color>", a.GetComponent<TestTile>().vec2);
                }
            }
            else
            {
                this.closeList.Add(this.openList.FirstOrDefault());
                this.ResetOpenList();
                this.SetMotherNode(this.openList.FirstOrDefault());
                this.openList.Clear();
                this.SetOpenList();
                this.OrderByList();
            }
            //else
            //{
            //    this.closeList.Add(this.openList.FirstOrDefault());
            //    this.ResetOpenList();
            //    var min = this.openList.OrderBy(x => x.GetComponent<TestTile>().f).ToList();
            //    this.SetMotherNode(min.FirstOrDefault());
            //    this.openList.Clear();
 
 
            //    this.SetOpenList();
            //    this.OrderByList();
            //    this.SaveMoveCost();
 
 
            //    if(this.CheckValueToOpenList())
            //    {
            //        Debug.Log("Mother node is change!!");
            //        this.SetOpenList();
            //        this.OrderByList();
            //        this.SaveMoveCost();
            //    }
            //}
        });
 
        this.btn2.onClick.AddListener(() =>
        {
            if (closeList.LastOrDefault() == this.targetNode)
            {
                Debug.Log("목표 위치에 도달했습니다.");
 
                foreach (var a in this.motherNodes)
                {
                    Debug.LogFormat("<color=red>{0}</color>", a.GetComponent<TestTile>().vec2);
                }
            }
            else
            {
                this.ResetOpenList();
                this.OrderByMin();
                var orderList = this.minList.OrderBy(x => x.GetComponent<TestTile>().f);
                this.SetMotherNode(orderList.FirstOrDefault());
                this.openList.Clear();
                this.SetOpenList();
 
 
                //오픈리스트 / 닫힌리스트 / minList G최소값만 있는 리스트
                //this.closeList.Add(this.minList.FirstOrDefault());
                //this.ResetOpenList();
                //var orderList = this.minList.OrderBy(x => x.GetComponent<TestTile>().f);
                //this.SetMotherNode(orderList.FirstOrDefault());
                //this.openList.Clear();
                //this.SetOpenList();
                //this.OrderByMin();
                //foreach(var nodes in this.openList)
                //{
                //    Debug.Log(nodes.GetComponent<TestTile>().vec2);
                //}
                foreach (var nodes in this.openList)
                {
                    if (nodes == this.targetNode && nodes.GetComponent<TestTile>().f == this.openList.FirstOrDefault().GetComponent<TestTile>().f)
                    {
                        this.motherNode = this.targetNode;
                        break;
                    }
                }
                
            }
        });
    }
 
    private bool CheckValueToOpenList()
    {
        var returnNode = this.motherNodes[this.motherNodes.Count - 2];
        var nextNode = this.openList.FirstOrDefault();
 
        var returnMotherDistance = Vector3.Distance(returnNode.transform.position, nextNode.transform.position);
        var returnTargetDistance = Vector3.Distance(returnNode.transform.position, this.targetNode.transform.position);
        var returnDistance = returnMotherDistance + returnTargetDistance;
 
        var resultCost = Vector3.Distance(returnNode.transform.position, this.motherNode.transform.position) + this.moveCost;
 
        if (returnMotherDistance < resultCost)
        {
            var sprite = this.motherNode.GetComponentInChildren<SpriteRenderer>();
            sprite.color = Color.white;
            this.SetMotherNode(returnNode);
            return true;
        }
        return false;
    }
 
    #region OrderBy
 
    private void SaveMoveCost()
    {
        this.moveCost = this.openList.FirstOrDefault().GetComponent<TestTile>().f;
    }
 
    private void OrderByList()
    {
        var list = this.openList.OrderBy(x => x.GetComponent<TestTile>().f).ToList();
        this.openList = list;
        this.OrderByMin();
    }
 
    private void OrderByMin()
    {
        var list = this.openList.OrderBy(x => x.GetComponent<TestTile>().g).ToList();
        int index = 0;
        foreach (var tile in list)
        {
            if (tile.GetComponent<TestTile>().g == list.FirstOrDefault().GetComponent<TestTile>().g)
            {
                this.minList.Add(list[index]);
            }
            index++;
        }
    }
 
    #endregion
 
    private void FindPath(GameObject target)
    {
        this.FindNodes();
    }
 
    private void FindNodes()
    {
        this.SetMotherNode(this.tiles[startX, startY]);
        this.SetOpenList();
        this.OrderByList();
    }
 
    private void ResetOpenList()
    {
        foreach (var tile in this.openList)
        {
            var sprite = tile.GetComponentInChildren<SpriteRenderer>();
            sprite.color = Color.white;
        }
        this.SetFalseArrow();
        this.SetFalseValue();
    }
 
 
    private void SetOpenList()
    {
        var motherX = this.motherNode.GetComponent<TestTile>().x - 1;
        var motherY = this.motherNode.GetComponent<TestTile>().y - 1;
        var maxX = this.motherNode.GetComponent<TestTile>().x + 1;
        var maxY = this.motherNode.GetComponent<TestTile>().y + 1;
        if (motherX < 0)
        {
            motherX = 0;
        }
        if (motherY < 0)
        {
            motherY = 0;
        }
 
        for (int i = motherX; i <= maxX; i++)
        {
            for (int j = motherY; j <= maxY; j++)
            {
                if (this.tiles[i, j].GetComponent<TestTile>().tileType == 0)
                {
                    this.openList.Add(this.tiles[i, j]);
                    this.SetG(this.tiles[i, j]);
                    this.SetH(this.tiles[i, j]);
                    this.SetF(this.tiles[i, j]);
                    var sprite = this.tiles[i, j].GetComponentInChildren<SpriteRenderer>();
                    sprite.color = Color.cyan;
                }
            }
        }
        this.TurnArrow();
    }
 
    private void SetMotherNode(GameObject mother)
    {
        this.motherNode = mother;
        this.motherNodes.Add(this.motherNode);
        this.motherNode.GetComponent<TestTile>().tileType = 2;
        Debug.LogFormat("Mother node : {0}"this.motherNode.GetComponent<TestTile>().f);
        var sprite = this.motherNode.GetComponentInChildren<SpriteRenderer>();
        sprite.color = Color.gray;
    }
 
 
    #region Arrow, FGH Value, Coordinate
    private void TurnArrow()
    {
        foreach (var tile in this.openList)
        {
            var script = tile.GetComponent<TestTile>();
            var xPos = this.motherNode.transform.position.x - script.Arrow.transform.position.x;
            var yPos = this.motherNode.transform.position.y - script.Arrow.transform.position.y;
            var rad = Mathf.Atan2(yPos, xPos) * Mathf.Rad2Deg;
            script.Arrow.transform.rotation = Quaternion.Euler(new Vector3(00, rad + 270));
 
            script.Arrow.SetActive(true);
        }
    }
 
    private void SetFalseArrow()
    {
        foreach (var tile in this.openList)
        {
            var script = tile.GetComponent<TestTile>();
            script.Arrow.SetActive(false);
        }
    }
 
    private void SetFalseValue()
    {
        foreach (var tile in this.openList)
        {
            var script = tile.GetComponent<TestTile>();
            script.textF.text = "F";
            script.textG.text = "G";
            script.textH.text = "H";
        }
    }
 
    private void SetCorrdinate()
    {
        for (int i = 0; i < this.row; i++)
        {
            for (int j = 0; j < this.col; j++)
            {
                this.coordinate[i, j] = new Vector2(i, j);
            }
        }
    }
 
    private void SetF(GameObject tile)
    {
        var tileScript = tile.GetComponent<TestTile>();
        tileScript.f = tileScript.g + tileScript.h;
        tileScript.textF.text = tileScript.f.ToString("f0");
    }
 
    private void SetG(GameObject tile)
    {
        var tileScript = tile.GetComponent<TestTile>();
        var targetScript = this.targetNode.GetComponent<TestTile>();
        var dis = (Vector2.Distance(tile.transform.position, this.motherNode.transform.position)) * 10;
        tileScript.textG.text = dis.ToString("f0");
        tileScript.g = dis;
    }
 
    private void SetH(GameObject tile)
    {
        var tileScript = tile.GetComponent<TestTile>();
        var targetScript = this.targetNode.GetComponent<TestTile>();
        var dis = (Vector2.Distance(tile.transform.position, this.targetNode.transform.position)) * 10;
        tileScript.textH.text = dis.ToString("f0");
        tileScript.h = dis;
    }
    #endregion
 
    #region CreateTiles
    private void CreateTiles()
    {
 
        for (int i = 0; i < this.row; i++)
        {
            for (int j = 0; j < this.col; j++)
            {
                var screenPos = Camera.main.ScreenToWorldPoint(new Vector2((j * 100+ 400, (i * -100+ 550));
                screenPos.z = 0;
                if (i == this.startX && j == this.startY)
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[1]);
                    this.tiles[i, j] = tile;
                    this.startNode = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.vec2 = this.coordinate[i, j];
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
                else if (i == this.targetX && j == this.targetY)
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[2]);
                    this.tiles[i, j] = tile;
                    this.targetNode = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.vec2 = this.coordinate[i, j];
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
                else if ((i >= 1 && i < 4&& j == 3)
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[0]);
                    this.tiles[i, j] = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.tileType = 1;
                    script.vec2 = this.coordinate[i, j];
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
                else
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[3]);
                    this.tiles[i, j] = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.vec2 = this.coordinate[i, j];
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
            }
        }
    }
    #endregion
}
 
cs


'Algorithm > 풀고있는 문제' 카테고리의 다른 글

A* Algorithm 좋은 영상  (0) 2019.05.23
A* Algorithm Simulation  (0) 2019.05.22
A* Algorithm 구현  (0) 2019.05.21
A* Algorithm 진행중  (0) 2019.05.17
:

A* Algorithm 진행중

Algorithm/풀고있는 문제 2019. 5. 17. 20:23

A* Algorithm

하나의 노드로부터 타겟 노드까지의 최단 경로를 찾는 알고리즘

f(n) = g(n) + h(n) 을 통해 최단 경로를 찾는다.

풀이는 집가서 써야지




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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Test0517 : MonoBehaviour
{
    public int row, col;
    public int startX, startY;
    public int targetX, targetY;
 
    private GameObject[] tilePrefabs;
    private GameObject[,] tiles;
    private GameObject motherNode;
    private GameObject startNode;
    private GameObject targetNode;
    private List<GameObject> listTile;
    private List<GameObject> openList;
    private List<GameObject> closeList;
    private List<GameObject> motherNodes;
 
    private Vector2[,] coordinate;
    
    void Start()
    {
        this.tilePrefabs = Resources.LoadAll<GameObject>("Tiles");
        this.coordinate = new Vector2[this.row, this.col];
        this.tiles = new GameObject[this.row, this.col];
        this.listTile = new List<GameObject>();
 
        this.SetCorrdinate();
        this.CreateTiles();
        
 
        this.SetMotherNode(this.tiles[startX, startY]);
        this.FindPath(this.tiles[25]);
 
    }
 
    private void FindPath(GameObject target)
    {
        this.FindNodes();
    }
 
    private void FindNodes()
    {
        var mother = this.motherNode.GetComponent<TestTile>();
        var motherX = this.motherNode.GetComponent<TestTile>().x - 1;
        var motherY = this.motherNode.GetComponent<TestTile>().y - 1;
        var maxX = this.motherNode.GetComponent<TestTile>().x + 1;
        var maxY = this.motherNode.GetComponent<TestTile>().y + 1;
        if (motherX < 0)
        {
            motherX = 0;
        }
        if(motherY < 0)
        {
            motherY = 0;
        }
 
        for (int i = motherX; i <= maxX; i++)
        {
            for (int j = motherY; j <= maxY; j++)
            {
                if (this.tiles[i, j].GetComponent<TestTile>().tileType == 0)
                {
                    this.listTile.Add(this.tiles[i, j]);
                    this.SetG(this.tiles[i, j]);
                    this.SetH(this.tiles[i, j]);
                    this.SetF(this.tiles[i, j]);
                    this.TurnArrow(this.tiles[i,j]);
                    var sprite = this.tiles[i, j].GetComponentInChildren<SpriteRenderer>();
                    sprite.color = Color.cyan;
                }
            }
        }
    }
 
    private void TurnArrow(GameObject tile)
    {
        var script = tile.GetComponent<TestTile>();
        var xPos = this.startNode.transform.position.x - script.Arrow.transform.position.x;
        var yPos = this.startNode.transform.position.y - script.Arrow.transform.position.y;
        var rad = Mathf.Atan2(yPos, xPos) * Mathf.Rad2Deg;
        script.Arrow.transform.rotation = Quaternion.Euler(new Vector3(00, rad+270));
 
        script.Arrow.SetActive(true);
    }
 
    private void SetMotherNode(GameObject mother)
    {
        this.motherNode = mother;
        this.motherNode.GetComponent<TestTile>().tileType = 2;
    }
 
    private void SetCorrdinate()
    {
        for (int i = 0; i < this.row; i++)
        {
            for (int j = 0; j < this.col; j++)
            {
                this.coordinate[i, j] = new Vector2(i, j);
            }
        }
    }
 
    private void SetF(GameObject tile)
    {
        var tileScript = tile.GetComponent<TestTile>();
        tileScript.f = tileScript.g + tileScript.h;
        tileScript.textF.text = tileScript.f.ToString();
    }
    private void SetG(GameObject tile)
    {
        var tileScript = tile.GetComponent<TestTile>();
        var targetScript = this.targetNode.GetComponent<TestTile>();
        var dis = (int)(Vector2.Distance(tile.transform.position, this.targetNode.transform.position)) * 10;
        Debug.Log(dis);
        tileScript.textH.text = dis.ToString();
        tileScript.h = dis;
    }
    private void SetH(GameObject tile)
    {
        var tileScript = tile.GetComponent<TestTile>();
        var targetScript = this.targetNode.GetComponent<TestTile>();
        var dis = (int)(Vector2.Distance(tile.transform.position, this.startNode.transform.position)) * 10;
        Debug.Log(dis);
        tileScript.textG.text = dis.ToString();
        tileScript.g = dis;
    }
 
 
    private void CreateTiles()
    {
 
        for (int i = 0; i < this.row; i++)
        {
            for (int j = 0; j < this.col; j++)
            {
                var screenPos = Camera.main.ScreenToWorldPoint(new Vector2((j * 100+ 400, (i * -100+ 550));
                screenPos.z = 0;
                if (i == this.startX && j == this.startY)
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[1]);
                    this.tiles[i, j] = tile;
                    this.startNode = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
                else if (i == this.targetX && j == this.targetY)
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[2]);
                    this.tiles[i, j] = tile;
                    this.targetNode = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
                else if ((i >= 1 && i < 4&& j == 3)
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[0]);
                    this.tiles[i, j] = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.tileType = 1;
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
                else
                {
                    var tile = GameObject.Instantiate(this.tilePrefabs[3]);
                    this.tiles[i, j] = tile;
                    var script = tile.GetComponent<TestTile>();
                    script.x = i;
                    script.y = j;
                    script.textCoord.text = script.x.ToString() + ", " + script.y.ToString();
                    tile.transform.position = screenPos;
                }
            }
        }
    }
}
 
cs


'Algorithm > 풀고있는 문제' 카테고리의 다른 글

A* Algorithm 좋은 영상  (0) 2019.05.23
A* Algorithm Simulation  (0) 2019.05.22
A* Algorithm 구현  (0) 2019.05.21
A* Algorithm 4방향/8방향 탐색  (0) 2019.05.20
:

Shader Graph Manual

Unity/3D 2019. 5. 15. 11:58

DOCS (Unity)

유니티 공식 Docs

https://docs.unity3d.com/Packages/com.unity.shadergraph@5.3/manual/Getting-Started.html


Tutorial (Unity Official)

유니티 공식 Tutorial

https://www.youtube.com/watch?v=V5XFrIhLpGQ&list=PLX2vGYjWbI0RyhAsNJg4sLLKgCZsRSim2&index=1


Tutorial (GAMEACADEMY.school)

Gameacademy 사이트에서 제공하는 Tutorial

https://gameacademy.school/shadergraph-tutorial/



ShaderGraph_ExampleLibrary (UnityTechnologies)

유니티 공식 ShaderGraph 예시

https://github.com/UnityTechnologies/ShaderGraph_ExampleLibrary

'Unity > 3D' 카테고리의 다른 글

Shader Graph  (0) 2019.05.13
: