'Unity/과제'에 해당되는 글 5건

  1. 2019.05.13 Isometric, 클릭시 좌표 출력하기
  2. 2019.05.09 2D Running Game 기본 시스템 만들기
  3. 2019.04.16 씬 전환 및 가서 공격하기
  4. 2019.04.16 왔다갔다 때리기
  5. 2019.04.11 0

Isometric, 클릭시 좌표 출력하기

Unity/과제 2019. 5. 13. 02:35


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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Text;
 
 
public class TestIsometric : MonoBehaviour
{
    public Button btn;
    public Camera camera;
    public GameObject tileParty;
    public GameObject isoTileParty;
    private float tileWidth = 0.64f;
    private float tileHeight = 0.64f;
    private float isoTileWidth = 0.64f;
    private float isoTileHeight = 0.32f;
    private int cntX = 0;
    private int cntY = 0;
 
    // Start is called before the first frame update
    void Start()
    {
        this.btn.onClick.AddListener(() =>
        {
            this.CreateIsoTile();
        });
    }
 
    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero);
            if(hit.collider!=null)
            {
                var script = hit.collider.GetComponent<TestisoTile>();
                Debug.LogFormat("This tile's coordinate : ({0},{1})", script.x, script.y);
            }
        }
    }
 
    public void CreateIsoTile()
    {
        var tileGo = GameObject.Instantiate(Resources.Load<GameObject>("isoTile"));
        tileGo.transform.SetParent(this.isoTileParty.transform);
        var txt = tileGo.GetComponentInChildren<TextMesh>();
        txt.text = string.Format("({0},{1})"this.cntX, this.cntY);
        var script = tileGo.GetComponent<TestisoTile>();
        script.x = this.cntX;
        script.y = this.cntY;
        tileGo.transform.position = this.MakeIsoTile(new Vector2(this.cntX, this.cntY));
        cntX++;
        if (this.cntX == 7)
        {
            this.cntX = 0;
            this.cntY++;
        }
        if (this.cntY == 4  )
 
        {
            this.btn.gameObject.SetActive(false);
        }
    }
 
    public Vector2 MakeIsoTile(Vector2 mapPos)
    {
        if(this.cntY >= 1)
        {
            var screenX = this.isoTileParty.transform.position.x + ((0.64f * -mapPos.y) + (0.64f * mapPos.x));
            var screenY = this.isoTileParty.transform.position.y + -(0.32f * (mapPos.y + mapPos.x));
            return new Vector2(screenX, screenY);
        }
        else
        {
            var screenX = this.isoTileParty.transform.position.x + mapPos.x * this.isoTileWidth;
            var screenY = this.isoTileParty.transform.position.y - mapPos.x * this.isoTileHeight;
            return new Vector2(screenX, screenY);
        }
    }
 
    public void CreateTile()
    {
        var tileGo = GameObject.Instantiate(Resources.Load<GameObject>("Tile"));
        tileGo.transform.SetParent(this.tileParty.transform);
        var txt = tileGo.GetComponentInChildren<TextMesh>();
        txt.text = string.Format("({0},{1})"this.cntX, this.cntY);
        tileGo.transform.position = this.MapToScreen(new Vector2(this.cntX, this.cntY));
        cntX++;
        if (this.cntX == 4)
        {
            this.cntX = 0;
            this.cntY++;
        }
        if (this.cntY == 4)
        {
            this.btn.gameObject.SetActive(false);
        }
    }
 
    public Vector2 MapToScreen(Vector2 mapPos)
    {
        //var screenX = mapPos.x * this.tileWidth + -10f * this.tileWidth;
        //var screenY = -(mapPos.y * this.tileHeight) + 3.6f;
        var screenX = this.tileParty.transform.position.x + mapPos.x * this.tileWidth;
        var screenY = this.tileParty.transform.position.y - mapPos.y * this.tileHeight;
 
        return new Vector2(screenX, screenY);
    }
 
    public Vector2 ScreenToMap(Vector2 screenPos)
    {
        //128,64 -> 2,1
        var mapX = (int)screenPos.x / this.tileWidth;
        var mapY = (int)screenPos.y / this.tileHeight;
 
        return new Vector2(mapX, mapY);
    }
}
 
 
cs


'Unity > 과제' 카테고리의 다른 글

2D Running Game 기본 시스템 만들기  (0) 2019.05.09
씬 전환 및 가서 공격하기  (0) 2019.04.16
왔다갔다 때리기  (0) 2019.04.16
0  (0) 2019.04.11
:

2D Running Game 기본 시스템 만들기

Unity/과제 2019. 5. 9. 19:05



수정해야 할 것 : UI 점수 갱신, 점프 모션 어색함 완화


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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
 
public class TestPlayer : MonoBehaviour
{
    public Animator anim;
 
    private void Awake()
    {
        this.anim = this.gameObject.GetComponent<Animator>();
        this.transform.position = new Vector3(-1.351f, 0.309f, 0);
    }
 
    private void Start()
    {
        this.anim.Play("fox_run");
    }
 
    public void Jump()
    {
        StartCoroutine(this.JumpImpl());
    }
 
    private IEnumerator JumpImpl()
    {
        this.anim.Play("fox_jump");
        this.transform.DOJump(this.transform.position, 0.3f, 10.5f);
        yield return new WaitForSeconds(this.anim.GetCurrentAnimatorStateInfo(0).length);
        this.anim.Play("fox_run");
    }
 
    private void OnTriggerEnter2D(Collider2D other)
    {
        other.gameObject.SetActive(false);
        var screenpos = Camera.main.WorldToScreenPoint(other.transform.position);
        var gemUiGo = Instantiate(Resources.Load<GameObject>("CherryImage"));
        gemUiGo.transform.SetParent(GameObject.Find("Canvas").transform, false);
        gemUiGo.transform.position = screenpos;        
        gemUiGo.transform.DOMove(GameObject.Find("CherryImage").transform.position, 0.5f).OnComplete(() =>
        {
            Destroy(gemUiGo);
        });
    }
}
 
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
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class TestSunnyLand : MonoBehaviour
{
    public GameObject backGround;
    public GameObject way;
    public GameObject player;
    public GameObject gemLayer;
    public Button jumpBtn;
    public List<GameObject> listCherry;
 
    private void Awake()
    {
        this.backGround.transform.position = new Vector3(000);
        this.way.transform.position = new Vector3(3.392575f, 0.1069814f, -0.06640625f);
    }
 
    private void Start()
    {
        this.jumpBtn.onClick.AddListener(() =>
        {
            var playerScript = this.player.GetComponent<TestPlayer>();
            playerScript.Jump();
        });
        this.GameStart();
    }
 
    public void GameStart()
    {
        foreach(var cherry in this.listCherry)
        {
            cherry.SetActive(true);
        }
        StartCoroutine(this.MoveBackGround());
 
        StartCoroutine(this.MoveWay());
 
        StartCoroutine(this.MoveGemLayer());
    }
 
    private IEnumerator MoveBackGround()
    {
        var bg = this.backGround.transform.position;
        var originPosition = bg;
        while(true)
        {
            if (this.backGround.transform.position.x > 0.35f)
            {
                this.backGround.transform.position = originPosition;
            }
            else
            {
                this.backGround.transform.position += new Vector3(0.03f * Time.deltaTime, 00);
            }
            yield return null;
        }
    }
 
    private IEnumerator MoveWay()
    {
        var pos = this.way.transform.position;
        var originPosition = pos;
        while(true)
        {
            if(this.way.transform.position.x <= -5.5f)
            {
                this.way.transform.position = originPosition;
            }
            this.way.transform.position -= new Vector3(0.9f * Time.deltaTime, 00);
            yield return null;
        }
    }
 
    private IEnumerator MoveGemLayer()
    {
        var pos = this.gemLayer.transform.position;
        var originPosition = pos;
        while (true)
        {
            if (this.gemLayer.transform.position.x < -9.03f)
            {
                foreach (var cherry in this.listCherry)
                {
                    if (!cherry.activeSelf)
                    {
                        cherry.SetActive(true);
                    }
                }
                this.gemLayer.transform.position = originPosition;
            }
            this.gemLayer.transform.position -= new Vector3(0.9f * Time.deltaTime, 00);
            yield return null;
        }
    }
}
 
cs


'Unity > 과제' 카테고리의 다른 글

Isometric, 클릭시 좌표 출력하기  (0) 2019.05.13
씬 전환 및 가서 공격하기  (0) 2019.04.16
왔다갔다 때리기  (0) 2019.04.16
0  (0) 2019.04.11
:

씬 전환 및 가서 공격하기

Unity/과제 2019. 4. 16. 18:57

App카메라 유지, 코루틴, Json, 익명함수, 이벤트 이용

App->Logo->Title(데이터로딩)->InGame 순으로 씬전환

#문법 공부 많이 해야함




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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
namespace minseok
{
    public partial class App : MonoBehaviour
    {
        public Camera uiCamera;
 
        //인스턴스화 될때
        private void Awake()
        {
            var oper = SceneManager.LoadSceneAsync("Logo");
            oper.completed += (asyncOper) =>
            {
                Debug.Log("logo scene 로드 완료");
                var logo = GameObject.FindObjectOfType<Logo>();
                logo.Init(this.uiCamera);
            };
            DontDestroyOnLoad(this);
        }
    }
}
 
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
42
43
44
45
46
47
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
namespace minseok
{
    public class Logo : MonoBehaviour
    {
        public UILogo uiLogo;
 
        public void Init(Camera uiCamera)
        {
            this.uiLogo.onFadeInComplete = () =>
            {
                var oper = SceneManager.LoadSceneAsync("Title");
                oper.completed += (asyncOper) =>
                {
                    Debug.Log("Title scene 로드 완료");
                    var title = GameObject.FindObjectOfType<Title>();
                    title.Init(uiCamera);
                };
                Debug.Log("fade in 완료");
                StopAllCoroutines();
            };
            
            this.uiLogo.onFadeOutComplete = () =>
            {
                Debug.Log("fade out 완료");
                //3초 후 실행
                StartCoroutine(this.WaitForSecond(3, () =>
                {
                    StartCoroutine(this.uiLogo.FadeIn());               
                }));
            };
 
            this.uiLogo.Init(uiCamera);
            StartCoroutine(this.uiLogo.FadeOut()); //1실행
        }
 
        private IEnumerator WaitForSecond(float sec, System.Action onCompleteWait)
        {
            yield return new WaitForSeconds(sec);
            onCompleteWait();
        }
    }
}
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
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using Newtonsoft.Json;
 
namespace minseok
{
    public class Title : MonoBehaviour
    {
        public UITitle uiTitle;
        public Button btn;
 
        private void Awake()
        {
            this.btn.onClick.AddListener(() =>
            {
                var oper = SceneManager.LoadSceneAsync("InGame");
                oper.completed += (asyncOperation) =>
                {
                    Debug.Log("InGame 씬 로드완료");
                };
            });
        }
 
        public void Init(Camera uiCamera)
        {
            this.DataLoad();
 
            this.uiTitle.onFadeOutComplete = () =>
            {
                Debug.Log("title의 fade in 완료");
                StopCoroutine(this.uiTitle.FadeOut());
            };
 
            this.uiTitle.Init(uiCamera);
            StartCoroutine(this.uiTitle.FadeOut());
        }
 
        private IEnumerator WaitForSecond(float sec, System.Action onCompleteWait)
        {
            yield return new WaitForSeconds(sec);
            onCompleteWait();
        }
 
        private void DataLoad()
        {
            var data = DataManager.GetInstance();
            var textAsset = Resources.Load<TextAsset>("Data/character_data");
            var json = textAsset.text;
            var dataJson = JsonConvert.DeserializeObject<CharacterData[]>(json);
            foreach(var datas in dataJson)
            {
                data.dicCharacterData.Add(datas.id, datas);
            }
 
            textAsset = Resources.Load<TextAsset>("Data/character_anim_data");
            json = textAsset.text;
            var animJson = JsonConvert.DeserializeObject<CharacterAnimData[]>(json);
            foreach(var datas in animJson)
            {
                data.dicCharacterAnim.Add(datas.id, datas);
            }
        }
    }
}
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
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
namespace minseok
{
    public class InGame : MonoBehaviour
    {
        private Character hero;
        private Character monster;
        private System.Action onCompleteAttack;
 
        private void Start()
        {
            this.hero = this.CreateCharacter(0);
            this.monster = this.CreateCharacter(1);
            this.StartGame();
        }
 
        private void StartGame()
        {
            this.hero.transform.LookAt(this.monster.transform);
            this.monster.transform.LookAt(this.hero.transform);
            this.hero.Move(this.monster, () =>
            {
                this.hero.anim.Play(DataManager.GetInstance().dicCharacterAnim[this.hero.info.id].idle_anim_name);
                this.hero.Attack(this.monster, this.onCompleteAttack);
            });
            this.onCompleteAttack = () =>
            {
                if(this.monster.info.hp > 0)
                {
                    this.hero.Attack(this.monster, this.onCompleteAttack);
                }
                else
                {
                    Debug.LogFormat("{0}를 처치했습니다!", DataManager.GetInstance().dicCharacterData[this.monster.info.id].name);
                    this.hero.anim.Play(DataManager.GetInstance().dicCharacterAnim[this.hero.info.id].idle_anim_name);
                }
            };
        }
 
        private Character CreateCharacter(int id)
        {
            var data = DataManager.GetInstance();
            var charPrefab = Resources.Load<GameObject>("Prefabs/Character");
            var charGo = GameObject.Instantiate<GameObject>(charPrefab);
            var modelPrefab = Resources.Load<GameObject>(data.dicCharacterData[id].prefab_name);
            var modelGo = GameObject.Instantiate<GameObject>(modelPrefab);
            var character = charGo.AddComponent<Character>();
            
            character.Model = modelGo;
            character.name = data.dicCharacterData[id].name;
            character.info = new CharacterInfo(id, data.dicCharacterData[id].hp, new Vector3(000));
 
            if(character.info.id == 1)
            {
                character.transform.position = new Vector3(505);
            }
            else
            {
                character.transform.position = character.info.position;
            }
 
            Debug.Log("캐릭터가 생성되었습니다.");
            return character;
        }
    }
}
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
namespace minseok
{
    public class DataManager
    {
        private static DataManager instance;
        public Dictionary<int, CharacterData> dicCharacterData = new Dictionary<int, CharacterData>();
        public Dictionary<int, CharacterAnimData> dicCharacterAnim = new Dictionary<int, CharacterAnimData>();
 
        private DataManager()
        {
 
        }
 
        public static DataManager GetInstance()
        {
            if(DataManager.instance == null)
            {
                DataManager.instance = new DataManager();
            }
            return DataManager.instance;
        }
    }
}
 
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
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 UnityEngine.UI;
 
namespace minseok
{
    public class UIBase : MonoBehaviour
    {
        public Canvas canvas;
        public Image dim;
        public System.Action onFadeOutComplete;
        public System.Action onFadeInComplete;
 
        public virtual void Init(Camera uiCamera)
        {
            this.canvas.worldCamera = uiCamera;
        }
 
        public IEnumerator FadeOut()
        {
            var color = this.dim.color;
            color.a = 1;
            this.dim.color = color;
 
            float alpha = color.a;
            while (true)
            {
                alpha -= 0.016f;
                color.a = alpha;
                this.dim.color = color;
                if (alpha <= 0)
                {
                    alpha = 0f;
                    break;
                }
                yield return null;
            }
            this.onFadeOutComplete();
        }
 
        public IEnumerator FadeIn()
        {
            Debug.Log("fadein호출");
            var color = this.dim.color;
            color.a = 0;
            this.dim.color = color;
 
            float alpha = color.a;
            while (true)
            {
                alpha += 0.016f;
                color.a = alpha;
                this.dim.color = color;
                if (alpha >= 1)
                {
                    alpha = 1f;
                    break;
                }
                yield return null;
            }
            this.onFadeInComplete();
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
namespace minseok
{
    public class UILogo : UIBase
    {
        public override void Init(Camera uiCamera)
        {
            base.Init(uiCamera);
        }
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
namespace minseok
{
    public class UITitle : UIBase
    {
        public override void Init(Camera uiCamera)
        {
            base.Init(uiCamera);
        }
    }
}
 
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
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
namespace minseok
{
    public class Character : MonoBehaviour
    {
        private Coroutine routine;
        public CharacterInfo info;
        public Animation anim;
        public GameObject model;
        public GameObject Model
        {
            get
            {
                return this.Model;
            }
            set
            {
                this.model = value;
                this.model.transform.SetParent(this.transform);
                this.anim = this.model.GetComponent<Animation>();
            }
        }
        
        public Character(CharacterInfo info, GameObject model)
        {
            this.info = info;
            this.Model = model;
        }
 
        public void Move(Character target, System.Action onCompleteMove)
        {
            StartCoroutine(this.MoveImpl(target, onCompleteMove));
            StopCoroutine(this.MoveImpl(target, onCompleteMove));
        }
        private IEnumerator MoveImpl(Character target, System.Action onCompleteMove)
        {
            Debug.Log("걸어간다");
            var data = DataManager.GetInstance();
            this.anim.Play(data.dicCharacterAnim[this.info.id].run_anim_name);
            var normVector = (target.transform.position - this.transform.position).normalized;
            var speed = normVector * 1.0f * Time.deltaTime;
            while(true)
            {
                var distance = Vector3.Distance(target.transform.position, this.transform.position);
                this.transform.position += speed;
                if(distance <= data.dicCharacterData[this.info.id].attack_range)
                {
                    break;
                }
                yield return null;
            }
            onCompleteMove();
        }
 
        public void Attack(Character target, System.Action onCompleteAttack)
        {
            if (this.routine != null)
            {
                StopCoroutine(this.routine);
            }
            this.routine = StartCoroutine(this.AttackImpl(target, onCompleteAttack));
        }
        private IEnumerator AttackImpl(Character target, System.Action onCompleteAttack)
        {
            Debug.Log("공격한다");
            var data = DataManager.GetInstance();
            this.anim.Play(data.dicCharacterAnim[this.info.id].attack_anim_name);
            yield return new WaitForSeconds(0.26f);
 
            Debug.LogFormat("{0}에게 {1}의 데미지를 입혔습니다!", data.dicCharacterData[target.info.id].name, data.dicCharacterData[this.info.id].damage);
            target.TakeDamage(data.dicCharacterData[this.info.id].damage);
            yield return new WaitForSeconds(0.86f);
 
            onCompleteAttack();
        }
 
        public void TakeDamage(int damage)
        {
            this.info.hp -= damage;
            if(this.info.hp <= 0)
            {
                this.anim.Play(DataManager.GetInstance().dicCharacterAnim[this.info.id].die_anim_name);
            }
        }
    }
}
 
cs


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;
 
namespace minseok
{
    public class CharacterAnimData
    {
        public int id;
        public string attack_anim_name;
        public string damage_anim_name;
        public string idle_anim_name;
        public string run_anim_name;
        public string die_anim_name;
    }
 
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
namespace minseok
{
    public class CharacterData
    {
        public int id;
        public string prefab_name;
        public string name;
        public int hp;
        public int damage;
        public float attack_range;
    }
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
namespace minseok
{
    public class CharacterInfo
    {
        public int id;
        public int hp;
        public Vector3 position;
 
        public CharacterInfo(int id, int hp, Vector3 position)
        {
            this.id = id;
            this.hp = hp;
            this.position = position;
        }
    }
}
 
cs


'Unity > 과제' 카테고리의 다른 글

Isometric, 클릭시 좌표 출력하기  (0) 2019.05.13
2D Running Game 기본 시스템 만들기  (0) 2019.05.09
왔다갔다 때리기  (0) 2019.04.16
0  (0) 2019.04.11
:

왔다갔다 때리기

Unity/과제 2019. 4. 16. 08:46
코루틴은 사용 후 항상 stop할 것

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public partial class App : MonoBehaviour
{
    private eSceneType sceneType;
 
    private void Awake()
    {
        this.sceneType = eSceneType.None;
        Object.DontDestroyOnLoad(this);
    }
 
    // Start is called before the first frame update
    void Start()
    {
        this.LoadScene(eSceneType.Logo);
    }
 
    private void LoadScene(eSceneType sceneType)
    {
        AsyncOperation asyncOperation = null;
        if(this.sceneType != sceneType)
        {
            this.sceneType = sceneType;
            asyncOperation = SceneManager.LoadSceneAsync((int)sceneType);
            asyncOperation.completed += (ao) =>
            {
                switch (this.sceneType)
                {
                    case eSceneType.Logo:
                        {
                            this.LoadScene(eSceneType.Title);
                        }
                        break;
                    case eSceneType.Title:
                        {
                            this.LoadScene(eSceneType.DataLoad);
                        }
                        break;
                    case eSceneType.DataLoad:
                        {
                            this.LoadScene(eSceneType.InGame);
                        }
                        break;
                    case eSceneType.InGame:
                        {
                            var inGame = GameObject.FindObjectOfType<InGame>();
                            inGame.Init();
                        }
                        break;
                }
            };
 
        }
    }
}
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public partial class App : MonoBehaviour
{
    public enum eSceneType
    {
        None = -1,
        App = 0,
        Logo = 1,
        Title = 2,
        DataLoad = 3,
        InGame = 4
    }
}
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
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
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Character : MonoBehaviour
{
    public CharacterInfo info;
    public Animation anim;
    private GameObject model;
    public GameObject Model
    {
        get
        {
            return this.model;
        }
        set
        {
            this.model = value;
            this.model.transform.SetParent(this.transform);
            this.anim = this.model.GetComponent<Animation>();
        }
    }
    public System.Action OnAttackComplete;
    private Coroutine routine;
 
    //생성자
    public Character(CharacterInfo info)
    {
        this.info = info;
    }
 
    //이동메서드
    public void Move(Vector3 targetPosition, System.Action onCompleteMove)
    {
        Debug.Log("Move호출");
        if(routine != null)
        {
            StopCoroutine(this.routine);
        }
        this.routine = StartCoroutine(this.MoveImpl(targetPosition, onCompleteMove));
    }
 
    //이동코루틴
    private IEnumerator MoveImpl(Vector3 targetPosition, System.Action onCompleteMove)
    {
 
        Debug.Log("moveImpl 호출");
        this.anim.Play(DataManager.GetInstance().dicCharacterAnimData[this.info.id].run_anim_name);
        var normVector = (targetPosition - this.transform.position).normalized;
        var speed = 1.0f;
        var moveVector = normVector * speed * Time.deltaTime;
        while(true)
        {
            this.transform.position += moveVector;
            var distance = Vector3.Distance(targetPosition, this.transform.position);
            if(distance <= 0.5f)
            {
                break;
            }
            yield return null;
        }
        onCompleteMove();
    }
 
    //공격메서드
    public void Attack(Character target)
    {
        Debug.Log("Attack 호출");
        if (routine != null)
        {
            StopCoroutine(this.routine);
        }
 
        this.routine = StartCoroutine(this.AttackImpl(target));
    }
 
    //공격코루틴
    private IEnumerator AttackImpl(Character target)
    {
        Debug.Log("attackImpl 호출");
        var attackAnimName = DataManager.GetInstance().dicCharacterAnimData[this.info.id].attack_anim_name;
        this.anim.Play(attackAnimName);
        yield return new WaitForSeconds(0.26f);
 
        Debug.LogFormat("{0}에게 {1}의 데미지를 입혔습니다!", DataManager.GetInstance().dicCharacterData[target.info.id].name, DataManager.GetInstance().dicCharacterData[this.info.id].damage);
        target.GetDamage(DataManager.GetInstance().dicCharacterData[this.info.id].damage);
        yield return new WaitForSeconds(0.46f);
        
        this.OnAttackComplete();
    }
 
    //피해메서드
    public void GetDamage(int damage)
    {
        this.info.hp -= damage;
        if (this.info.hp <= 0)
        {
            this.gameObject.GetComponentInChildren<Animation>().Play(DataManager.GetInstance().dicCharacterAnimData[this.info.id].die_anim_name);
        }
        else
        {
            this.gameObject.GetComponentInChildren<Animation>().Play(DataManager.GetInstance().dicCharacterAnimData[this.info.id].hit_anim_name);
        }
    }
}
cs



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;
using UnityEngine.SceneManagement;
 
public class DataLoad : MonoBehaviour
{
    private AsyncOperation asyncOperation;
 
    // Start is called before the first frame update
    void Start()
    {
        //데이터 로드, 데이터 적재
        Debug.Log("DataLoad 씬 Start()");
        DataManager dataManager = DataManager.GetInstance();
        dataManager.LoadDatas();
    }
}
 
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
42
43
44
45
46
47
48
49
50
51
52
53
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
 
public class DataManager
{
    private static DataManager instance;
    public Dictionary<int, CharacterData> dicCharacterData;
    public Dictionary<int, CharacterAnimData> dicCharacterAnimData;
 
    //생성자
    private DataManager()
    {
        this.dicCharacterAnimData = new Dictionary<int, CharacterAnimData>();
        this.dicCharacterData = new Dictionary<int, CharacterData>();
    }
 
    //인스턴스리턴
    public static DataManager GetInstance()
    {
        if(DataManager.instance == null)
        {
            DataManager.instance = new DataManager();
        }
        return DataManager.instance;
    }
 
    //제이슨 파일로드
    public void LoadDatas()
    {
        //캐릭터데이터
        var textAsset = Resources.Load<TextAsset>("Datas/character_data");
        var json = textAsset.text;
        var arrJson = JsonConvert.DeserializeObject<CharacterData[]>(json);
        foreach (var data in arrJson)
        {
            this.dicCharacterData.Add(data.id, data);
        }
        //애니메이션데이터
        var textAsset2 = Resources.Load<TextAsset>("Datas/character_anim_data");
        var json2 = textAsset2.text;
        var arrJson2 = JsonConvert.DeserializeObject<CharacterAnimData[]>(json2);
        foreach (var data in arrJson2)
        {
            this.dicCharacterAnimData.Add(data.id, data);
        }
        Debug.LogFormat("dicCharacterData  {0}개"this.dicCharacterData.Count);
        Debug.LogFormat("dicCharacterAnimData  {0}개"this.dicCharacterAnimData.Count);
    }
 
}
 
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
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class InGame : MonoBehaviour
{
    private Character hero;
    private Character monster;
    private bool completeMethod;
 
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("InGame Start 메서드 실행");
        this.hero.anim.Play(DataManager.GetInstance().dicCharacterAnimData[this.hero.info.id].idle_anim_name);
        this.monster.anim.Play(DataManager.GetInstance().dicCharacterAnimData[this.monster.info.id].idle_anim_name);
 
        this.hero.Move(this.monster.transform.position, () =>
        {
            Debug.Log("사정거리에 도달했습니다.");
            this.hero.anim.Play(DataManager.GetInstance().dicCharacterAnimData[this.hero.info.id].idle_anim_name);
            this.hero.Attack(this.monster);
        });
        this.hero.OnAttackComplete = () => {
 
            this.hero.anim.Play(DataManager.GetInstance().dicCharacterAnimData[this.hero.info.id].idle_anim_name);
            if (this.monster.info.hp > 0)
            {
                this.hero.Attack(this.monster);
            }
            else
            {
                this.hero.anim.Play(DataManager.GetInstance().dicCharacterAnimData[this.hero.info.id].idle_anim_name);
            }
        };
 
        this.hero.transform.LookAt(new Vector3(101));
        this.hero.Move(new Vector3(101), () =>
        {
            Debug.Log("초기위치에 도달했습니다.");
            this.hero.anim.Play(DataManager.GetInstance().dicCharacterAnimData[this.hero.info.id].idle_anim_name);
        });
    }
 
    public void Init()
    {
        Debug.Log("InGame 스크립트의 Init메서드 호출");
        var data = DataManager.GetInstance();
        this.hero = this.CreateCharacter(0);
 
        this.monster = this.CreateCharacter(1);
        this.hero.transform.position = new Vector3(101);
        this.monster.transform.position = new Vector3(505);
        this.hero.transform.LookAt(this.monster.transform);
        this.monster.transform.LookAt(this.hero.transform);
    }
 
    public Character CreateCharacter(int id)
    {
        var data = DataManager.GetInstance();
 
        //캐릭터생성
        var characterPrefab = Resources.Load<GameObject>("Prefabs/Character");
        var characterGo = GameObject.Instantiate<GameObject>(characterPrefab);
        var modelPrefab = Resources.Load<GameObject>(data.dicCharacterData[id].prefab_name);
        var modelGo = GameObject.Instantiate<GameObject>(modelPrefab);
        var character = characterGo.AddComponent<Character>();
        character.Model = modelGo;
        character.name = data.dicCharacterData[id].name;
        character.info = new CharacterInfo(id, data.dicCharacterData[id].anim_data_id, data.dicCharacterData[id].hp);
        character.transform.position = character.info.position;
 
        Debug.Log("캐릭터 생성됨");
        return character;
    }
}
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class Logo : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Logo씬 스크립트의 Start메서드가 호출됨");
        Debug.Log("Logo를 보여줍니다.");
    }
}
 
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class Title : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Title Scene Title Script 호출");
        Debug.LogFormat("DataLoad씬 호출완료");
    }
}
 
cs


'Unity > 과제' 카테고리의 다른 글

Isometric, 클릭시 좌표 출력하기  (0) 2019.05.13
2D Running Game 기본 시스템 만들기  (0) 2019.05.09
씬 전환 및 가서 공격하기  (0) 2019.04.16
0  (0) 2019.04.11
:

0

Unity/과제 2019. 4. 11. 22: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
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Character : MonoBehaviour
{
    private float moveSpeed = 1;
    private float distance;
    private float attackRange;
    private float translation = 0;
    private int attackDamage;
    private int hp;
    private int count = 0;
    private int attackCount = 1;
    private Vector3 normVector;
    private Vector3 targetPosition;
    private Character target;
    private Animation anim;
    private bool isMoveStart = false;
    private bool isAttackStart = false;
 
    void Awake()
    {
        this.anim = this.gameObject.GetComponent<Animation>();
    }
 
    // Start is called before the first frame update
    void Start()
    {
 
    }
 
    //초기화
    public void Init(int attackDamage, int hp, float attackRange, Vector3 initPosition)
    {
        this.attackDamage = attackDamage;
        this.hp = hp;
        this.attackRange = attackRange;
        this.gameObject.transform.position = initPosition;
    }
 
    //공격
    public void AttackMotion()
    {
        switch (this.attackCount)
        {
            case 1:
                {
                    this.anim.Play("attack_sword_01");
                }
                break;
        }
            //case 2:
            //    {
            //        this.anim.Play("attack_sword_02");
            //    }
            //    break;
            //case 3:
            //    {
            //        this.anim.Play("attack_sword_03");
            //    }
        //    //    break;
        //}
        //this.attackCount++;
        //if (this.attackCount > 3)
        //{
        //    this.attackCount = 1;
        //}
 
    }
 
    //피해받음
    public void GetDamage(int damage)
    {
        this.hp -= damage;
        Debug.Log("데미지를 입었습니다.");
    }
 
    //이동
    public void Move()
    {
        this.gameObject.transform.position += this.normVector * this.moveSpeed * Time.deltaTime;
        this.distance = Vector3.Distance(this.targetPosition, this.gameObject.transform.position);
 
        if (this.distance <= this.attackRange)
        {
            Debug.Log("이동완료");
            this.anim.Play("idle@loop");
            this.isAttackStart = true;
            this.isMoveStart = false;
        }
    }
 
    //이동시작
    public void MoveStart(Character target)
    {
        this.target = target;
        Debug.Log("이동시작");
        this.isMoveStart = true;
        this.targetPosition = this.target.gameObject.transform.position;
        this.normVector = (this.targetPosition - this.gameObject.transform.position).normalized;
 
        //animation start
        this.anim.Play("run@loop");
 
        //방향 변경
        this.gameObject.transform.LookAt(targetPosition);
    }
 
    // Update is called once per frame
    void Update()
    {
 
        this.translation += Time.deltaTime * 10;
        //Debug.Log(translation);
 
        if (isMoveStart)
        {
            this.Move();
        }
        else if (isAttackStart)
        {
            //Debug.Log(this.translation);
            if (this.attackCount == 1)
            {
                if (this.translation >= 6.48f)
                {
                    this.translation = 0;
                    this.target.GetDamage(this.attackDamage);
                }
                else if (this.translation <= 6.47f)
                {
                    this.AttackMotion();
                }
            }
        }
 
    }
}
 
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class App : MonoBehaviour
{
    public Character hero;
    public Character monster;
 
    void Awake()
    {
        this.hero.Init(15700.5f, new Vector3(000));
        this.monster.Init(1050, 1f, new Vector3(505));
        this.hero.MoveStart(this.monster);
 
    }
    // Start is called before the first frame update
    void Start()
    {
    }
 
    // Update is called once per frame
    void Update()
    {
        
    }
}
 
cs


'Unity > 과제' 카테고리의 다른 글

Isometric, 클릭시 좌표 출력하기  (0) 2019.05.13
2D Running Game 기본 시스템 만들기  (0) 2019.05.09
씬 전환 및 가서 공격하기  (0) 2019.04.16
왔다갔다 때리기  (0) 2019.04.16
: