'C#/실습'에 해당되는 글 45건

  1. 2019.12.18 12.18 인벤토리만들기
  2. 2019.12.17 12.17 Unity Editor 활용해 실시간으로 Json 파일 만들기
  3. 2019.12.16 12.16 UI 버튼 만들기
  4. 2019.12.13 12.13 캐릭터 선택하기(랜덤포함)
  5. 2019.12.09 12.09 충돌감지와 sprite활용하기(delegate)
  6. 2019.12.06 12.06 드래곤플라이트 구현
  7. 2019.12.05 12.05 유닛 바라보기 (LookAt 메서드 사용X) 1
  8. 2019.11.29 11.29 캐릭터 움직이기 (Coroutine, Update 비교 및 활용)

12.18 인벤토리만들기

C#/실습 2019. 12. 18. 16:48

Scene: TestPopup 

코드:

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
public class TestHQ : MonoBehaviour
{
    public UIPopup_SelectedStage popup_SelectedStage;
    public Button stageBtn;
    public Image dim;
    public List<UserItem> userItems = new List<UserItem>();
    UserItem[] arrUserItems;
    ItemData[] ItemDatas;
    private void Awake()
    {
        string json = File.ReadAllText("ItemData.json"); 
        ItemDatas = JsonConvert.DeserializeObject<ItemData[]>(json); // 아이템 row 데이터 로드
        if (File.Exists("UserItemData.json")) //유저가 갖고있던 아이템 로드
        {
            Debug.Log("Real user Items");
            string userItemJson = File.ReadAllText("UserItemData.json");
            arrUserItems = JsonConvert.DeserializeObject<UserItem[]>(userItemJson);            
            foreach(UserItem userItem in arrUserItems)
            {
                userItems.Add(userItem);
            }
        }
        else//기존 유저 아이템 파일이 없다면
        {
            Debug.Log("Sample user Items");
            arrUserItems = new UserItem[3];
            arrUserItems[0= new UserItem(ItemDatas[0].id, ItemDatas[0].name, ItemDatas[0].iconName, 2);
            arrUserItems[1= new UserItem(ItemDatas[1].id, ItemDatas[1].name, ItemDatas[1].iconName, 2);
            arrUserItems[2= new UserItem(ItemDatas[2].id, ItemDatas[2].name, ItemDatas[2].iconName, 2);
            foreach (UserItem userItem in arrUserItems)
            {
                userItems.Add(userItem);
            }
        }
        
 
    }
    void Start()
    {
 
        popup_SelectedStage.Init(new UserInfo("홍길동"315753603920), userItems);
        stageBtn.onClick.AddListener(() =>
        {
            popup_SelectedStage.Show();
            dim.gameObject.SetActive(true);
        });
        popup_SelectedStage.closeBtn.onClick.AddListener(() =>
        {
            popup_SelectedStage.Hide();
            dim.gameObject.SetActive(false);
        });
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class ItemData
{
    public int id;
    public string name;
    public string iconName;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
public class UIPopup_SelectedStage : MonoBehaviour
{
    public Button closeBtn;
    public Text text;
    UserInfo userInfo;
    public InventoryItems[] inventoryItems;
    public SpriteAtlas atlas;
 
    public void Init(UserInfo userInfo, List<UserItem> userItems)
    {
        for(int i =0; i<inventoryItems.Length; i++)//초기화
        {
            if(i<9)
            {
                inventoryItems[i].iconStatus = eItemIconStatus.none; //열려있는 아이템칸 설정
            }
            else
            {
                inventoryItems[i].iconStatus = eItemIconStatus.locked; // 닫혀있는 아이템 칸 설정
            }
        }
        this.userInfo = userInfo;
        this.text.text = "UserName: \t" + userInfo.userName + "\n Attack: \t\t" + userInfo.atk + "\n Defense: \t" + userInfo.def + "\n Health: \t\t" + userInfo.hp;        
        for(int i=0; i<userItems.Count; i++// 아이템칸에 차례대로 내 아이템 넣기.
        {
            inventoryItems[i].iconStatus = eItemIconStatus.have;
            inventoryItems[i].userItems = userItems[i];
            inventoryItems[i].gameObject.transform.GetChild(1).gameObject.transform.GetChild(0).GetComponent<Text>().text = inventoryItems[i].userItems.count.ToString();
        }
        for(int i = 0; i<inventoryItems.Length; i++// 아이콘의 상태에 따라 스프라이트 바꾸기
        {
            switch(inventoryItems[i].iconStatus)
            {
                case eItemIconStatus.locked :
                    {
                        inventoryItems[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("MyInfo/inventory_item_lock"));
                        inventoryItems[i].gameObject.transform.GetChild(0).gameObject.SetActive(false);
                        inventoryItems[i].gameObject.transform.GetChild(1).gameObject.SetActive(false);
                        break;
                    }
                case eItemIconStatus.have:
                    {
                        for(int j = 0; j< userItems.Count; j++)
                        {
                            string iconName = string.Format("MyInfo/{0}",inventoryItems[j].userItems.iconName);
                            inventoryItems[j].gameObject.transform.GetChild(0).gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>(iconName));
                        }
                        break;
                    }
                case eItemIconStatus.none:
                    {
                        inventoryItems[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("MyInfo/inventory_item_bg"));
                        inventoryItems[i].gameObject.transform.GetChild(0).gameObject.SetActive(false);
                        inventoryItems[i].gameObject.transform.GetChild(1).gameObject.SetActive(false);
                        break;
                    }
            }
        }
 
    }
    public void Show()
    {
        this.gameObject.SetActive(true);
    }
    public void Hide()
    {
        this.gameObject.SetActive(false);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class UserInfo
{
    public string userName;
    public int level;
    public int atk;
    public int def;
    public int hp;
    public UserInfo(string userName, int level, int atk, int def, int hp)
    {
        this.userName = userName;
        this.level = level;
        this.atk = atk;
        this.def = def;
        this.hp = hp;
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public enum eItemIconStatus { have, none, locked}
public class InventoryItems : MonoBehaviour
{
    public eItemIconStatus iconStatus;
    public UserItem userItems;
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class UserItem 
{
    public int id;
    public string name;
    public string iconName;
    public int count;
    public UserItem(int id, string name, string iconName, int count)
    {
        this.id = id;
        this.name = name;
        this.iconName = iconName;
        this.count = count;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

:

12.17 Unity Editor 활용해 실시간으로 Json 파일 만들기

C#/실습 2019. 12. 17. 17:52

Unity 파일명: Study_015 Title

 

코드:

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
 
public enum eStars { one, two, three, none }
 
public class HQ : MonoBehaviour
{    
    public StageInfo[] stageInfos = new StageInfo[18];
    public eStageStatus[] stageStatuses;
    public eStars[] stars;
    public Stage[] stages;
    private GameObject star1;
    private GameObject star2;
    private GameObject star3;
    int starsN = 0;
 
    // Start is called before the first frame update
    private void Awake()
    {
        star1 = Resources.Load<GameObject>("Stage/Star1");
        star2 = Resources.Load<GameObject>("Stage/Star2");
        star3 = Resources.Load<GameObject>("Stage/Star3");
        
 
    }
    void Start()
    {
        for(int i=0; i<stages.Length; i++)
        {
            stages[i].stageStatus = stageStatuses[i];
            stages[i].gameObject.transform.GetChild(0).gameObject.GetComponent<Text>().text = i.ToString();
        }
 
        for (int i = 0; i<stages.Length; i++// stage status 체크
        {
            if(stages[i].stageStatus == eStageStatus.Cleared) //깬 경우
            {
                stages[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("Stage/Cleared"));
                stages[i].Stars = (int)stars[starsN];
                starsN++;
                switch(stages[i].Stars)
                {
                    case 0:
                        {
                            var model = Instantiate(star1);
                            model.transform.SetParent(stages[i].gameObject.transform.GetChild(1).transform, false);
                            model.transform.localPosition = Vector3.zero;
                            break;
                        }
                        
                    case 1:
                        {
                            var model = Instantiate(star2);
                            model.transform.SetParent(stages[i].gameObject.transform.GetChild(1).transform, false);
                            model.transform.localPosition = Vector3.zero;
                            break;
                        }
                    case 2:
                        {
                            var model = Instantiate(star3);
                            model.transform.SetParent(stages[i].gameObject.transform.GetChild(1).transform, false);
                            model.transform.localPosition = Vector3.zero;
                            break;
                        }                        
                }
            }
            else if(stages[i].stageStatus == eStageStatus.Opened)
            {
                stages[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("Stage/Opened"));
            }
            else if(stages[i].stageStatus == eStageStatus.Locked)
            {
                stages[i].gameObject.GetComponent<Image>().sprite = Instantiate(Resources.Load<Sprite>("Stage/Locked"));
                stages[i].gameObject.transform.GetChild(0).gameObject.SetActive(false);
            }
        }
    }
    public void GenerateJson()
    {
        for (int i = 0; i < stageInfos.Length; i++)
        {
            //stageInfos[i].stageID = i;
            //stageInfos[i].stageStatus = (int)stageStatuses[i];
            //stageInfos[i].stars = (int)stars[i];
 
            StageInfo stageInfo = new StageInfo(i, (int)stageStatuses[i], (int)stars[i]);
            stageInfos[i] = stageInfo;
            
        }
        string json = JsonConvert.SerializeObject(stageInfos);
        File.WriteAllText("StageInfo", json);
 
    }
 
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
 
[CustomEditor(typeof(HQ))]
 
public class GenerateJson : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();
 
        HQ generator = (HQ)target;
        if (GUILayout.Button("Generate Json"))
        {
            generator.GenerateJson();
        }
    }
 
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class StageInfo
{
    public int stageID = 0;
    public int stageStatus;
    public int stars = 0;
    public StageInfo(int stageID, int stageStatus, int stars)
    {
        this.stageID = stageID;
        this.stageStatus = stageStatus;
        this.stars = stars;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public enum eStageStatus { Opened, Cleared, Locked}
public class Stage : MonoBehaviour
{
    public eStageStatus stageStatus;
    private int stars = 0;
    public int Stars { get { return stars; } set { stars = value; } }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

'C# > 실습' 카테고리의 다른 글

12.18 인벤토리만들기  (0) 2019.12.18
12.16 UI 버튼 만들기  (0) 2019.12.16
12.13 캐릭터 선택하기(랜덤포함)  (0) 2019.12.13
12.09 충돌감지와 sprite활용하기(delegate)  (0) 2019.12.09
12.06 드래곤플라이트 구현  (0) 2019.12.06
:

12.16 UI 버튼 만들기

C#/실습 2019. 12. 16. 17:04

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Title : MonoBehaviour
{
    enum eMenuType { Items, Shop, Message, Mission, Ranking, Settings};
    public UIButtonMenu[] arrBtnMenu;
    public Sprite[] sprites;
    public string[] btnMenuNames;
    // Start is called before the first frame update
    void Start()
    {                
        for(int i = 0; i<this.arrBtnMenu.Length; i++)
        {
            eMenuType menus = (eMenuType)i;
            this.arrBtnMenu[i].Init(menus.ToString(),sprites[i]);
            Button btn = arrBtnMenu[i].gameObject.transform.GetChild(1).GetComponent<Button>();
            btn.onClick.AddListener(() =>
            {
                Debug.LogFormat("selected Menu: {0}, {1} i: {2}", menus.ToString(), (int)menus);
            });
            
        }    
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIButtonMenu : MonoBehaviour
{
    public Image icon;
    public Text textBtnName;
    public Button btn;
 
    public void Init(string btnName, Sprite spIcon)
    {
        this.textBtnName.text = btnName;
        this.icon.sprite = spIcon;
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class UISelectedButton : MonoBehaviour
{
    public Button btn;
    public System.Action Onselected;
    public Text text;
    void Start()
    {        
        this.btn.onClick.AddListener(() =>
        {
            this.Onselected();
        });
    }
    public void Init(string text)
    {
        this.gameObject.transform.GetChild(1).gameObject.SetActive(false);
        this.text.text = text;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

Horizontal LayOut Group 컴포넌트를 이용해 더욱 쉽게 정렬을 할 수 있었다.

 

:

12.13 캐릭터 선택하기(랜덤포함)

C#/실습 2019. 12. 13. 17:07

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Ingame : MonoBehaviour
{
    public UISelectedButton[] btns;
    public UISelectedButton randomBtn;
    public string[] btnNames;
    public Image image;
    private Coroutine changeC;
    private GameObject selectedObject;
    public Button selectBtn;
    public Text selectedText;
    public void Awake()
    {
 
        Debug.Log("Ingame: Awake");
 
    }
    private void Start()
    {
        selectBtn.onClick.AddListener(() =>
        {
            StopAllCoroutines();
            this.selectedText.text = this.selectedObject.transform.GetChild(0).GetComponent<Text>().text;
        });
        int i = 0;
        foreach(var btn in btns)
        {
            btn.Onselected = () =>
            {
                foreach(var btn2 in btns)
                {
                    btn2.gameObject.transform.GetChild(1).gameObject.SetActive(false);
                }
                StopAllCoroutines();
                btn.gameObject.transform.GetChild(1).gameObject.SetActive(true);
                this.selectedObject = btn.gameObject;
                this.image.sprite = btn.gameObject.GetComponent<Image>().sprite;
            };
            Debug.Log(btnNames[i]);
            btn.Init(btnNames[i]);
            i++;
        }
        randomBtn.Onselected = () =>
        {
            changeC = StartCoroutine(changeImage());
            foreach (var btn2 in btns)
            {
                btn2.gameObject.transform.GetChild(1).gameObject.SetActive(false);
                this.selectedObject = randomBtn.gameObject;
                randomBtn.gameObject.transform.GetChild(1).gameObject.SetActive(true);
 
            }
        };
        randomBtn.Init("random");
 
    }
    IEnumerator changeImage()
    {
        int i=0;
        while(true)
        {
            if(i >= 4)
            {
                i = 0;
            }
            this.image.sprite = btns[i].gameObject.GetComponent<Image>().sprite;
            this.selectedObject = btns[i].gameObject;
            yield return new WaitForSeconds(0.2f);
            i++;
        }
    }
    public void Init()
    {
        Debug.Log("게임 초기화");
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class UISelectedButton : MonoBehaviour
{
    public Button btn;
    public System.Action Onselected;
    public Text text;
    void Start()
    {        
        this.btn.onClick.AddListener(() =>
        {
            this.Onselected();
        });
    }
    public void Init(string text)
    {
        this.gameObject.transform.GetChild(1).gameObject.SetActive(false);
        this.text.text = text;
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

씬전환은 덤이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class App : MonoBehaviour
{
    private void Awake()
    {
    }
    void Start()
    {
        var oper = SceneManager.LoadSceneAsync("Ingame", LoadSceneMode.Additive);
        oper.completed += (ao) =>
        {
            Debug.Log("Ingame 씬 로드완료");
 
        };
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
:

12.09 충돌감지와 sprite활용하기(delegate)

C#/실습 2019. 12. 9. 17:25

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
 
public class App : MonoBehaviour
{
    public Button btnShoot;
    public Transform bulletInitPoint;
    private GameObject bulletPrefab;
    private Sprite explosionsprite;
    
    // Start is called before the first frame update
    void Start()
    {
        this.LoadResources();
        this.btnShoot.onClick.AddListener(() =>
        {
            Debug.Log("발사!");
            this.Shoot();
 
        });
    }
    private void LoadResources()
    {
        this.bulletPrefab = Resources.Load<GameObject>("Bullet");
        this.explosionsprite = Resources.Load<Sprite>("explosion3");
 
    }
    private void Shoot()
    {
        GameObject bulletModel = Instantiate(bulletPrefab);
        Bullet bullet = bulletModel.AddComponent<Bullet>();
        bulletModel.transform.position = this.bulletInitPoint.position;
        bullet.ShootCoroutine = bullet.ShootImple();
        StartCoroutine(bullet.ShootCoroutine);
        bullet.del = () =>
        {
            StopCoroutine(bullet.ShootCoroutine);
            GameObject explosionGO = new GameObject("explosion");
            explosionGO.transform.position = bullet.transform.position;
            SpriteRenderer spriteRenderer = explosionGO.AddComponent<SpriteRenderer>();
            spriteRenderer.sprite = Instantiate(explosionsprite);
            Animator animator = explosionGO.AddComponent<Animator>();
            animator.runtimeAnimatorController = 
            (RuntimeAnimatorController)RuntimeAnimatorController.Instantiate(
            Resources.Load("ExplosionCon"typeof(RuntimeAnimatorController)));
            explosion explosion = explosionGO.AddComponent<explosion>();            
            Destroy(bullet.gameObject);
 
        };
        
        
        
        
    }
    
    
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class explosion : MonoBehaviour
{
    public void whenExplode()
    {
        Destroy(this.transform.root.gameObject);
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Bullet : MonoBehaviour
{
    public Action del;
    public IEnumerator ShootCoroutine;
    // Start is called before the first frame update
    void Start()
    {
        
    }
    //private void OnCollisionEnter(Collision collision)
    //{                
    //    App.del();        
    //}
    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "wall")
        {
            this.del();
        }
        
    }
    public IEnumerator ShootImple()
    {
        while (true)
        {
            var vc = this.transform.up;
            this.transform.position += vc * 1 * Time.deltaTime;
 
            yield return null;
        }
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

참조:

Sprite 파일

https://www.pngguru.com/free-transparent-background-png-clipart-zceay

 

Sprite GameMaker: Studio Animation 2D computer graphics, explosion sprite transparent background PNG clipart | PNGGuru

PNG Clipart Information Dimensions 960x384px File size 113.87KB MIME type Image/png dominant color orange Resize PNG Clipart online resize by width resize by height

www.pngguru.com

스프라이트 애니메이션

https://m.blog.naver.com/PostView.nhn?blogId=heartybrain1&logNo=221142037112&proxyReferer=https%3A%2F%2Fwww.google.com%2F

 

유니티 - 스프라이트 시트(sprite sheet) 사용하기, 스프라이트 애니메이션

유니티에서 sprite sheet 사용하기, sprite 애니메이션 1)스프라이트 시트(sprite sheet)는 2D 애니메이션...

blog.naver.com

코드에서 애니메이션 바꾸기

https://playground10.tistory.com/95

 

[유니티] 코드에서 애니메이션 바꾸기

프리팹은 하나이고 애니메이션만 계속 코드에서 동적으로 바꾸고 싶을 때 아래와 같이 해주면 됩니다. 1. 먼저 해당 프리팹에 animator 컴포넌트를 추가해줍니다. (기존에 프리팹을 Player라고 만들었고 스크립트..

playground10.tistory.com

 

:

12.06 드래곤플라이트 구현

C#/실습 2019. 12. 6. 17:16

코드:

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Ship : MonoBehaviour
{
    public Transform bulletInitPoint;
    public Vector3 targetV;
    public GameObject model;
    GameObject prefab;
    GameObject modelBullet;
 
    // Start is called before the first frame update
    void Start()
    {
        prefab = Resources.Load<GameObject>("Prefabs/fireball-blue-big");
    }
    public void Attack()
    {
        StartCoroutine("MakeBulletForward");
        StartCoroutine("MakeBulletSide1");
        StartCoroutine("MakeBulletSide2");
 
    }
    IEnumerator MakeBulletSide1()
    {
        while (true)
        {
            GameObject bulletGO = new GameObject("bullet");
            bulletGO.transform.position = bulletInitPoint.position;
            Bullet bullet = bulletGO.AddComponent<Bullet>();
            modelBullet = Instantiate(prefab);
 
            modelBullet.transform.SetParent(bulletGO.transform, false);
            modelBullet.transform.localPosition = Vector3.zero;
            bullet.MoveSide1();
            yield return new WaitForSeconds(1f);
        }
    }
    IEnumerator MakeBulletSide2()
    {
        while (true)
        {
            GameObject bulletGO = new GameObject("bullet");
            bulletGO.transform.position = bulletInitPoint.position;
            Bullet bullet = bulletGO.AddComponent<Bullet>();
            var model = Instantiate(prefab);
            model.transform.SetParent(bulletGO.transform, false);
            model.transform.localPosition = Vector3.zero;
            bullet.MoveSide2();
            yield return new WaitForSeconds(1f);
        }
    }
 
    IEnumerator MakeBulletForward()
    {
        while(true)
        {
            GameObject bulletGO = new GameObject("bullet");           
            bulletGO.transform.position = bulletInitPoint.position;
            Bullet bullet = bulletGO.AddComponent<Bullet>();
            var model = Instantiate(prefab);
            model.transform.SetParent(bulletGO.transform, false);
            model.transform.localPosition = Vector3.zero;
            bullet.Move();
            yield return new WaitForSeconds(1f);
        }
        
        
    }
    
    
    // Update is called once per frame
    void Update()
    {
        {
            if(this.transform.position.x >= -3.5f)
            {
                this.transform.position += Vector3.left * 2 * Time.deltaTime;
            }
        }
        {
            if (this.transform.position.x <= 3.5f )
                this.transform.position += Vector3.right * 2 * Time.deltaTime;
        }
        if (Input.GetKey(KeyCode.UpArrow))
        {
            if ( this.transform.position.y <= 6f)
                this.transform.position += Vector3.up * 2 * Time.deltaTime;
        }
        {
            if (this.transform.position.y >= -6f )
                this.transform.position += Vector3.down * 2 * Time.deltaTime;
        }
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Bullet : MonoBehaviour
{
    Coroutine coroutineMove;
    // Start is called before the first frame update
    void Start()
    {
    }
    public void Move()
    {
        coroutineMove = StartCoroutine("MoveC");
 
    }
    public void MoveSide2()
    {
        StartCoroutine("MoveSideC2");
        StartCoroutine("MoveC");
    }
    IEnumerator MoveSideC2()
    {
        while (true)
        {
            var speed = 2;
 
            this.transform.position += -this.transform.right * speed * Time.deltaTime;
            if (this.transform.position.y >= 6f || this.transform.position.x <= -3.6f || this.transform.position.x >= 3.6f)
            {
                Destroy(this.gameObject);
            }
            yield return null;
        }
    }
    public void MoveSide1()
    {
        StartCoroutine("MoveSideC1");
        StartCoroutine("MoveC");
    }
    IEnumerator MoveSideC1()
    {
        while (true)
        {
            var speed = 2;
 
            this.transform.position += this.transform.right * speed * Time.deltaTime;
            if (this.transform.position.y >= 6f || this.transform.position.x <= -3.6f || this.transform.position.x >= 3.6f)
            {
                Destroy(this.gameObject);
            }
            yield return null;
        }
    }
    IEnumerator MoveC()
    {
        while (true)
        {
            var speed = 2;
            this.transform.position += this.transform.up * speed * Time.deltaTime;
            if (this.transform.position.y >= 6f)
            {
                Destroy(this.gameObject);
            }
            yield return null;
        }
    }
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class App2 : MonoBehaviour
{
    public Ship ship;
    public Button btnAttack;
    // Start is called before the first frame update
    void Start()
    {
        btnAttack.onClick.AddListener(() =>
        {
            ship.Attack();
        });
    }
 
    // Update is called once per frame
    void Update()
    {
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class BGScroller : MonoBehaviour
{
    private MeshRenderer render;
    private float offset;
    public float speed;
    // Start is called before the first frame update
    void Start()
    {
        render = GetComponent<MeshRenderer>();
    }
 
    // Update is called once per frame
    void Update()
    {
        offset += Time.deltaTime * speed;
        render.material.mainTextureOffset = new Vector2(0, offset);
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

참조:

무한 스크롤 배경:https://www.youtube.com/watch?v=asraLkuR3Jg

:

12.05 유닛 바라보기 (LookAt 메서드 사용X)

C#/실습 2019. 12. 5. 17:28

코드:

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
 
public class App2 : MonoBehaviour
{
    public GameObject model1;
    public GameObject model2;
    public Button btn;
    float angle;
    // Start is called before the first frame update
    void Start()
    {
        btn.onClick.AddListener(() =>
        {
 
            angle = Vector3.Angle(model2.transform.position - model1.transform.position, model1.transform.forward);
            Debug.Log(angle);
            if (Vector3.Dot(model1.transform.right, model2.transform.position - model1.transform.position) >= 0f)
            {
                model1.transform.rotation = model1.transform.rotation * Quaternion.Euler(0, angle, 0);
            }
            else
            {
                model1.transform.rotation = model1.transform.rotation * Quaternion.Euler(0-angle, 0);
 
            }
 
 
        });
    }
 
    // Update is called once per frame
    void Update()
    {
        //Debug.Log(angle);
 
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

그냥 A 와 B사이의 벡터를 구하고 A가 바라보는 벡터의 각을 구하기엔 B가 A의 오른쪽에 있든 왼쪽에 있든 같은 angle값이 나오기때문에 구분이 불가능했다.

따라서 A의 right 벡터와 A,B사이 벡터의 내적을 구하고 이것이 0보다 큰지 작은지를 비교해 이를 해결했다.

:

11.29 캐릭터 움직이기 (Coroutine, Update 비교 및 활용)

C#/실습 2019. 11. 29. 16:11

Move(Coroutine)을 누른후

코드:

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
using UnityEngine;
public class App : MonoBehaviour
{
    public Button btnMoveCoroutine;
    public Button btnMoveUpdate;
    public Hero hero;
    public GameObject targetPoint;
    // Start is called before the first frame update
    void Start()
    {
        GameObject heroGO = new GameObject("Hero");
        hero = heroGO.AddComponent<Hero>();
 
        string path = string.Format("Prefabs/{0}""ch_01_01");
        var prefab = Resources.Load<GameObject>(path);
        var model = Instantiate(prefab);
        model.transform.SetParent(heroGO.transform, false);
        model.transform.localPosition = Vector3.zero;
        hero.model = model;
 
        hero.onMove = (target) =>
        {
            var dis = Vector3.Distance(hero.transform.position, target.transform.position);
            var vc = target.transform.position - hero.transform.position;
            var dir = vc.normalized;
            var speed = 1;
            hero.transform.position += dir * speed * Time.deltaTime;
            if (dis <= 0.5f)
            {
                hero.transform.position = target.transform.position;
                hero.model.GetComponent<Animation>().Play("idle@loop");
                hero.isMove = false;
            }
        };
 
        btnMoveCoroutine.onClick.AddListener(() =>
        {
            hero.Move2(targetPoint);
        });
        btnMoveUpdate.onClick.AddListener(() => {
            hero.Move(targetPoint);
        });
 
    }
 
    // Update is called once per frame
    void Update()
    {
 
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
 
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Hero : MonoBehaviour
{
    public bool isMove;
    public Action<GameObject> onMove;
    public GameObject target;
    public GameObject model;
    IEnumerator onMoveCoroutine;
    // Start is called before the first frame update
    void Start()
    {
        onMoveCoroutine = OnMoveCoroutine();
    }
 
    public void Move(GameObject target)
    {
        this.target = target;
        isMove = true;
    }
    public void Move2(GameObject target)
    {
 
        this.target = target;
        //isMove = true;
        this.model.GetComponent<Animation>().Play("run@loop");
        StartCoroutine(onMoveCoroutine);
    }
    public void Update()
    {
        if (this.isMove == true)
        {
            this.model.GetComponent<Animation>().Play("run@loop");
            this.onMove(target);
        }        
        if (this.transform.position == target?.transform.position)
        {
            StopCoroutine(onMoveCoroutine);
        }
    }
 
    IEnumerator OnMoveCoroutine()
    {
        while (true)
        {
            var dis = Vector3.Distance(this.transform.position, target.transform.position);
            var vc = target.transform.position - this.transform.position;
            var dir = vc.normalized;
            var speed = 1;
            this.transform.position += dir * speed * 0.01f;
            this.transform.LookAt(target.transform);
            if (dis <= 0.1f)
            {
                this.model.GetComponent<Animation>().Play("idle@loop");
                this.transform.position = target.transform.position;
                //isMove = false;
            }
            yield return new WaitForSeconds(0.01f);
        }
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
: