상세 컨텐츠

본문 제목

Unity 5Runs 과제.

C#/과제

by McRobbin 2020. 5. 9. 16:55

본문

HomeworkAssets.unitypackage
0.05MB

과제 파일 올립니다.

 

처음 시작시 모습입니다. 캐릭터 생성 버튼이 있고 간단한 맵과 지물이 있습니다.

캐릭터 생성 버튼 클릭시 캐릭터가 생성됩니다.

 

다섯 영웅이 모였을 때의 모습입니다. 캐릭터 생성시 다섯개의 프리팹 중 랜덤으로 골라

게임 오브젝트를 생성합니다. 다음 다섯개의 미리 지어진 이름으로 세팅되며 속도가 램덤으로

정해집니다.

다섯이 모였을 경우 출발 버튼이 활성화 됩니다.

 

 

다섯이 달리는 모습입니다. 속도가 달라 뒤처지는 영웅들이 보입니다.

 

 

도착 했을때의 모습입니다. 1등은 덤블링을, 2, 3등은 아이들, 4, 5등은 죽는 모션을 반복합니다.

다섯이 다 도착하면 결과 버튼이 활성화 됩니다.

 

 

다음 결과창 입니다.

1, 2, 3등이 미리 준비된 맵으로 이동하며 단상위에 올라갑니다.

결과 하면으로 이름, 등수, 속도가 텍스트로 표시됩니다.

 

마지막으로 코드 올리고 마무리 하겠습니다.

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
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using UnityEngine.UI;
 
public class App : MonoBehaviour
{
    public static float GoalZ = 5.0f;
 
    public string[] names;
    public GameObject[] prefabs;
    public Button createBtn;
    public Button startBtn;
    public Button resultBtn;
    public Camera mainCam;
    public Camera resultCam;
    public Text resultText;
 
 
    private List<Hero> heros;
    private float margin;
    private int grade;
 
 
 
    void Start()
    {
        this.margin = -2.0f;
        this.heros = new List<Hero>();
        this.grade = 1;
 
        this.mainCam.enabled = true;
        this.resultCam.gameObject.SetActive(false);
        this.resultCam.enabled = false;
 
        //생성버튼 클릭시
        this.createBtn.onClick.AddListener(() =>
        {
 
            //버튼 클릭시 지정된 이름 갯수보다 작은 동안만 생성.
            if (heros.Count < names.Length)
            {
                System.Random rand = new System.Random();
 
                //히어로, 히어로 프리팹을 게임 오브젝트로 생성 및 부모로 설정
                var heroGo = Instantiate(Resources.Load<GameObject>("Prefabs/Hero"));
                var heroModelGo = Instantiate(prefabs[rand.Next(prefabs.Length)]);
                var heroComp = heroModelGo.AddComponent<Hero>();
                heroModelGo.transform.SetParent(heroGo.transform, false);
 
                //히어로 초기설정.
                heroGo.transform.position = new Vector3(margin++00);
                heroComp.Init(names[this.heros.Count],
                    (float)rand.NextDouble() + 0.5f,
                    new Vector3(heroGo.transform.position.x, 0, App.GoalZ));
 
                this.heros.Add(heroComp);
            }
 
            //이름 갯수만큼 히어로가 만들어 졌을 때.
            if(heros.Count == names.Length)
            {
                this.startBtn.gameObject.SetActive(true);
            }
 
        });
 
        //시작 버튼 클릭시.
        this.startBtn.onClick.AddListener(() =>
        {
            if (heros.Count == names.Length)
            {
                foreach(var hero in heros)
                {
                    if (!hero.IsGoal)
                        hero.HeroRun();
                }
            }
        });
 
        //결과 버튼 클릭시.
        this.resultBtn.onClick.AddListener(() =>
        {
            this.heros.Sort();
            this.mainCam.enabled = false;
            this.mainCam.gameObject.SetActive(false);
            this.resultCam.gameObject.SetActive(true);
            this.resultCam.enabled = true;
 
            heros[0].transform.position = new Vector3(0, 12f, 0);
            heros[0].transform.forward = Vector3.right;
            heros[1].transform.position = new Vector3(011.3f, -1.5f);
            heros[1].transform.forward = Vector3.right;
            heros[2].transform.position = new Vector3(010.9f, 1.5f);
            heros[2].transform.forward = Vector3.right;
 
            this.resultText.text = "";
            for(int i = 0; i < 3; i++)
                this.resultText.text += string.Format("이름 : {0}, 등수 : {1}, 속도 : {2}\n",
                    heros[i].HeroName, heros[i].Grade, heros[i].Speed);
 
            this.resultText.gameObject.SetActive(true);
        });
        
    }
 
    void Update()
    {
 
        //도착했으나 등수가 부여되지 않은 영웅 가져와 등수 부여.
        if (heros.FindAll(x => x.IsGoal && x.Grade == 0).Count > 0)
        {
            var needGradeHeros = heros.FindAll(x => x.IsGoal
                && x.Grade == 0);
 
            needGradeHeros.ForEach(x => x.SetGrade(this.grade++));
        }
 
        //모두 도착했을 때.
        else if(heros.Count == names.Length && heros.FindAll(x => x.IsGoal).Count == heros.Count)
        {
            this.resultBtn.gameObject.SetActive(true);
        }
 
    }
 
}
 
 
cs

App.cs 코드 입니다.

저는 카메라를 두개 사용했습니다. 달리는 장면을 찍을 카메라와 미리 만들어진 결과 맵을 찍을 카메라가 있습니다.

결과 버튼 클릭시 미리 만들어진 맵의 단상에 1등부터 3등까지 데려다가 올려놓습니다. (같은 객체)

 

App에서는 캐릭터를 만들고 처음 Init하고 hero의 상태만 바꿔주며 hero는 상태에 따라 움직임을 달리합니다.

 

 

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
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
 
public class Hero : MonoBehaviour, IComparable
{
    public enum eState
    {
        Idle,
        Run,
        Tumbling,
        Die
    }
 
    private Animation anim;
 
    private string heroName;
    public string HeroName { get { return this.heroName; }}
 
    private float speed;
    public float Speed { get { return this.speed; } }
 
    private bool isGoal;
    public bool IsGoal { get { return this.isGoal; } set { this.isGoal = value; } }
 
    private Vector3 goal;
    public Vector3 Goal { get {return this.goal; } }
 
    private eState heroState;
    public eState HeroState { get { return this.heroState; } set { this.heroState = value; } }
 
    private int grade;
    public int Grade { get { return this.grade; } }
 
    public void Init(string name, float speed, Vector3 goal)
    {
        this.isGoal = false;
        this.heroName = name;
        this.speed = speed;
        this.goal = goal;
        this.heroState = eState.Idle;
        this.grade = 0;
    }
 
    public void HeroRun()
    {
        this.heroState = eState.Run;
    }
 
    public void SetGrade(int grade)
    {
        this.grade = grade;
        //1등은 텀블링 상태로 전환,
        if (this.grade == 1)
            this.heroState = eState.Tumbling;
 
        //2, 3등은 아이들 상태로 전환.
        else if (this.grade == 2 || this.grade == 3)
            this.heroState = eState.Idle;
 
        //나머지는 죽는 상태로 전환.
        else
            this.heroState = eState.Die;
 
        Debug.LogFormat("이름 : {0}, {1}등, 상태 : {2}"this.heroName, this.grade, this.heroState);
 
    }
 
    void Start()
    {
        this.anim = this.gameObject.GetComponent<Animation>();
    }
 
    void Update()
    {
        switch (this.heroState)
        {
            case eState.Run:
                this.anim.Play("run@loop");
                if(transform.position.z > goal.z)
                {
                    this.isGoal = true;
                    this.heroState = eState.Idle;
                }
 
                else if(!this.isGoal)
                    this.gameObject.transform
                    .Translate(transform.forward * this.speed * Time.deltaTime);
                break;
 
            case eState.Idle:
                this.anim.Play("idle@loop");
                break;
 
            case eState.Die:
                this.anim.Play("die");
                break;
 
            case eState.Tumbling:
                this.anim.Play("tumbling");
                break;
 
            default:
                break;
        }
    }
 
    public int CompareTo(System.Object obj)
    {
        Hero other = obj as Hero;
        return this.grade.CompareTo(other.grade);
    }
 
}
 
 
cs

hero.cs 파일 입니다.

Update 실행시 상태에 따라 행동을 달리합니다.

 

히어로들이 모두 도착했을 때 등수에 따라 히어로를 정렬했습니다.

List.Sort()를 사용하기 위해 IComparable을 상속받아 CompareTo를 구현했습니다.

 

App은 히어로의 Init과 SetState를 통해서 조작하도록 했습니다.

 

히어로는 enum state를 가지도록 했습니다.

 

과제 마치겠습니다.

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

2048 콘솔 게임.  (0) 2020.05.01
과제 - 롤 챔프, 스킨 구매 시뮬레이션..?  (0) 2020.04.30
레시피 과제.  (0) 2020.04.17
홍길동과 임꺽정의 전투 클래스 사용.  (0) 2020.04.10
과제 04-03  (0) 2020.04.03

관련글 더보기