[Unity] 몬스터 캐릭터에 상태패턴 적용

APP 2020. 2. 21. 12:20

몬스터 콜라이더에 센터값 this.boxCollider.center = new Vector3(01.2f, 1); 을 잘못지정해서 영웅이 몬스터를 찾아도 Ray로 공격가능한지 체크를 못하는 문제가 발생---------->Vector3(0,1.2f,0)으로 변경

 

 

 

몬스터의 상태를 enum으로 정의하고 상태전환만 외부에서 해주면, 몬스터가 스스로 행동을 바꾸도록 만들었다.

 

Before

Monster.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
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
396
397
398
399
400
401
402
403
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class TestMonster : MonoBehaviour
{
    public DefenseMonsterData data; //monster_data.json의 내용 중 하나
    public float hp; //Init시 초기화
    public bool isTargetedByBomber; //폭탄병의 타겟이되었는가
    public NavMeshAgent agent;
    public Animator anim;
    public GameObject model;
    public BoxCollider boxCollider;
    public SkinnedMeshRenderer skinnedMeshRenderer;
    public TestFence fence;
    public Material defaultMaterial;
    public Material whiteMaterial;
    public System.Action OnCompleteMove;//NavMesh이동이 끝나면 호출
    public System.Action<float> OnDamagedCall;//맞은 시점에 호출
    public System.Action OnHit;//이벤트에서 공격시점에 호출
    public System.Action OnHudTextCall;//맞은 시점에 HUD호출
    public Coroutine coMoveByNav;
    public Coroutine coMove;
    public Coroutine coMoveAhead;
    public Coroutine coAttack;
    public Coroutine coDead;
    public Coroutine coKnockBack;
    public Coroutine coCheckHp;
    public System.Action OnMonsterDie;
    public System.Action OnMonsterDead;
    public System.Action<float> AttackCplAction;
 
    public void Init(DefenseMonsterData data, TestFence fence, Material mat)
    {
       
        this.data = data;
        this.hp = data.maxHp;
 
        var monsterAtttackAction = this.gameObject.transform.GetChild(0).gameObject.AddComponent<MonsterAtttackAction>();
        monsterAtttackAction.monsterAttackAction = (monster, dmg) => { AttackCplAction(dmg); };
 
        this.isTargetedByBomber = false;
        this.fence = fence;
        this.whiteMaterial = mat;
        if (model == null)
        {
            this.model = this.transform.GetChild(0).gameObject;
        }
        this.model.transform.localPosition = Vector3.zero;
 
        if (agent == null)
        {
            this.agent = this.gameObject.AddComponent<NavMeshAgent>();
        }
        if (anim == null)
        {
            this.anim = this.gameObject.GetComponentInChildren<Animator>();
        }
        if (boxCollider == null)
        {
            this.boxCollider = this.gameObject.AddComponent<BoxCollider>();
            this.boxCollider.size = new Vector3(131);
            this.boxCollider.center = new Vector3(01.2f, 1);
            this.boxCollider.isTrigger = true;
        }
        this.gameObject.layer = LayerMask.NameToLayer("Monster"); //레이어를 몬스터로
 
        this.agent.stoppingDistance = 1f;
 
        this.skinnedMeshRenderer = this.gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
        this.defaultMaterial = this.skinnedMeshRenderer.material;
 
        this.CheckHp();
    }
    public void SetNavMeshAgent()
    {
 
    }
 
    public enum eMonsterType { RunTwoAttack = 1, WalkOneAttack, CrawlBiting }
    void Start()
    {
        this.OnDamagedCall = (damage) =>
        {
            //Debug.Log("좀비가 맞았습니다");
            Hit(damage);
        };
 
        //this.OnHit = () =>
        //{
        //    //Debug.Log("Fence.OnDamageCall");
 
        //    this.fence.OnDamagedCall();
        //};
 
    }
    private void CheckHp()
    {
        coCheckHp = StartCoroutine(CheckHpImpl());
    }
    IEnumerator CheckHpImpl()
    {
        while (true)
        {
            //if (this.name == "Monster02(Clone)")
            //    Debug.Log($"CheckHp           {hp}            {this.name}");
 
            yield return null;
            if (this.hp <= 0)
            {
                this.agent.isStopped = true;
                this.Die();
            }
        }
    }
    public void Move(Vector3 pos) // 몬스터가 이동하는 매서드 (NavMesh없이)
    {
        switch ((eMonsterType)data.attackType)
        {
            case (eMonsterType.RunTwoAttack):
                {
                    this.anim.Play("Monster_Run");
                }
                break;
            case (eMonsterType.WalkOneAttack):
                {
                    this.anim.Play("Monster_Walk");
                }
                break;
            case (eMonsterType.CrawlBiting):
                {
                    this.anim.Play("Monster_Crawl");
                }
                break;
            default:
                break;
 
        }
        coMove = StartCoroutine(MoveImpl(pos));
    }
    IEnumerator MoveImpl(Vector3 pos)
    {
        while (true)
        {
            yield return null;
            var dir = (pos - this.gameObject.transform.position).normalized;
            var dis = (pos - this.gameObject.transform.position).magnitude;
            this.gameObject.transform.LookAt(dir);
 
            if (dis > 0.5f)
            {
                this.gameObject.transform.position += dir * data.moveSpeed * Time.deltaTime;
            }
            else
            {
                MoveAhead();
                StopCoroutine(coMove);
                break;
            }
        }
 
 
 
    }
 
    public void MoveByNavMesh(Vector3 pos) // 몬스터가 이동하는 매서드 (NavMesh로)
    {
        this.agent.destination = pos;
        this.agent.speed = data.moveSpeed;
        switch ((eMonsterType)data.attackType)
        {
            case (eMonsterType.RunTwoAttack):
                {
                    this.anim.Play("Monster_Run");
                }
                break;
            case (eMonsterType.WalkOneAttack):
                {
                    this.anim.Play("Monster_Walk");
                }
                break;
            case (eMonsterType.CrawlBiting):
                {
                    this.anim.Play("Monster_Crawl");
                }
                break;
        }
        Check(pos);
    }
 
 
    public void Check(Vector3 Pos)
    {
        coMoveByNav = StartCoroutine(CheckImpl(() =>
        {
            this.agent.isStopped = true;
            MoveAhead();
        }));
 
    }
    IEnumerator CheckImpl(System.Action OnCompleteMove) // 목표지점으로 이동하면서 목표지점에 도달하면 앞으로이동
    {
        while (true)
        {
            if (!agent.pathPending)
            {
 
                if (agent.remainingDistance <= agent.stoppingDistance)
                {
                    //if (!agent.hasPath || agent.velocity.sqrMagnitude < 2.1f)
                    //{
                    //Debug.Log("Check Completed");
 
                    //agent.SetDestination(this.transform.position);
                    OnCompleteMove();
                    break;
                    //}
                }
            }
            yield return null;
        }
    }
 
    public void MoveAhead()  //-z방향으로 전진
    {
        //Debug.Log("MoveAhead");
 
        coMoveAhead = StartCoroutine(MoveAheadImpl());
    }
    IEnumerator MoveAheadImpl()
    {
        switch ((eMonsterType)data.attackType)
        {
            case (eMonsterType.RunTwoAttack):
                {
                    this.anim.Play("Monster_Run");
                }
                break;
            case (eMonsterType.WalkOneAttack):
                {
                    this.anim.Play("Monster_Walk");
                }
                break;
            case (eMonsterType.CrawlBiting):
                {
                    this.anim.Play("Monster_Crawl");
                }
                break;
        }
        while (true)
        {
            yield return null;
 
            this.gameObject.transform.position += Vector3.back * data.moveSpeed * Time.deltaTime;
 
            this.gameObject.transform.rotation = Quaternion.Euler(01800);
 
            var dis = (this.gameObject.transform.position.z - fence.transform.position.z);
            //정지조건이 z가 81보다 작으면, 으로 되어있음 다른 조건으로 교체 필요
            if (dis < 1.5f)
            {
                break;
            }
        }
    }
    public void Attack()
    {
        StopCoroutine(coMoveAhead);
        coAttack = StartCoroutine(AttackImpl());
    }
    IEnumerator AttackImpl()
    {
        while (true)
        {
            switch ((eMonsterType)data.attackType)
            {
                case (eMonsterType.RunTwoAttack):
                    {
                        this.anim.Play("Monster_TwoAttack");
                    }
                    break;
                case (eMonsterType.WalkOneAttack):
                    {
                        this.anim.Play("Monster_OneAttack");
                    }
                    break;
                case (eMonsterType.CrawlBiting):
                    {
                        this.anim.Play("Monster_Biting");
                    }
                    break;
            }
            
            yield return new WaitForSeconds(3f);
        }
    }
    public void Hit(float damage)
    {
 
        if (this.hp > 0)
        {
            this.hp -= damage;
            StartCoroutine(HitImpl());
 
            if (this.hp <= 0)
            {
 
                OnMonsterDie();
            }
        }
        else
        {
            //Debug.Log($"{this.gameObject.name} Died");
            OnMonsterDie();
        }
    }
    IEnumerator HitImpl()
    {
 
        //메시를 하얗게 바꿔봄
        skinnedMeshRenderer.material = whiteMaterial;
        yield return new WaitForSeconds(0.2f);
        skinnedMeshRenderer.material = defaultMaterial;
 
        //HUDText를 올린다
        //OnHudTextCall();
 
 
        // 쉐이더를 standard => Unlit / Texture로 바꿔봄
        //meshR.material.shader = Shader.Find("Standard");
        //yield return new WaitForSeconds(0.2f);
        //meshR.material.shader = Shader.Find("Unlit/Texture");
    }
 
    public void Die()
    {
        StopAllCoroutines();
        this.skinnedMeshRenderer.material = defaultMaterial;
        if (this.gameObject.activeInHierarchy)
        {
 
            //Debug.Log($"{this.name}///DieCoroutine");
            this.agent.speed = 0;
            coDead = StartCoroutine(DieImpl());
        }
 
    }
    IEnumerator DieImpl()
    {
        this.anim.Play("Monster_Die1");
        yield return new WaitForSeconds(2.9f);
        OnMonsterDead();
    }
 
    public void KnockBack()
    {
        if (coKnockBack == null)
        {
            if (this.gameObject.activeInHierarchy)
            {
                coKnockBack = StartCoroutine(KnockBackImpl());
            }
        }
    }
    IEnumerator KnockBackImpl()
    {
        if (this.hp > 0)
        {
            for (int i = 0; i < 20; i++)
            {
                this.transform.position += Vector3.forward * 10 * Time.deltaTime;
                yield return null;
            }
            StopCoroutine(coKnockBack);
            if (this.agent.isStopped == false)
            {
                //if (coAttack != null)
                //{
                //    Debug.Log("-----------------coAttack Stop");
 
                //    StopCoroutine(coAttack);
                //    MoveAhead();
                //}
            }
            else
            {
                if (coAttack != null)
                {
                    Debug.Log("-----------------coAttack Stop");
 
                    StopCoroutine(coAttack);
                    MoveAhead();
                }
            }
        }
    }
 
}
 
 
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

After

 

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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class TestMonster : MonoBehaviour
{
    public DefenseMonsterData data; //monster_data.json의 row
    public float hp; //몬스터의 현재hp Init함수에서 data.maxHp로 초기화됨
 
    public TestFence fence; //공격대상인 Fence
 
    public bool isTargetedByBomber; //폭탄병의 중복타겟이 되지 않기위한 변수
 
    public NavMeshAgent agent;  //NavAgent
    public Vector3 navDestination;  //NavAgent의 목적지
    public Animator animator;   //Animator
    public GameObject model;    //Monster의 model
    public BoxCollider boxCollider; //Collider, Fence와 충돌감지
    public SkinnedMeshRenderer skinnedMeshRenderer; //피격시 깜빡이는 효과를 위한 MeshRenderer    
    public Material defaultMaterial;    //기본 머티리얼
    public Material whiteMaterial;  //하얀 머티리얼 
 
 
    public System.Action OnCompleteMove;//NavMesh이동이 끝나면 호출
 
    public System.Action<float> OnDamagedMonster;//맞은 시점에 호출    
 
    public System.Action OnHit;//이벤트에서 공격시점에 호출
 
    public System.Action OnMonsterDie;
    public System.Action OnMonsterDead;
    public System.Action<float> AttackCplAction;
 
    private Coroutine coCheckHp; //자신의 체력을 확인하기위한 코루틴
    public Coroutine coHit; //피격시 몬스터 자체 이펙트 수행을 위한 코루틴
    private Coroutine coBehavior;   //행동 코루틴
    public enum eMonsterState { MOVE, FOLLOW, ATTACK, DIE, KNOCKBACK } //몬스터 상태
    public enum eMonsterType { RunTwoAttack = 1, WalkOneAttack, CrawlBiting }   //몬스터 타입
 
    void Start()
    {
        this.OnDamagedMonster = (damage) =>
        {            
            Hit(damage);
        };
    }
 
    #region INIT
    public void Init(Vector3 navDestination, DefenseMonsterData data, TestFence fence, Material mat)
    {
        this.navDestination = navDestination;
 
        this.data = data;
        this.hp = data.maxHp;
        this.fence = fence;
        this.whiteMaterial = mat;
 
        var monsterAtttackAction = this.gameObject.transform.GetChild(0).gameObject.AddComponent<MonsterAtttackAction>();
        monsterAtttackAction.monsterAttackAction = (monster, dmg) => { AttackCplAction(dmg); };
 
        this.isTargetedByBomber = false;
 
        if (model == null)
        {
            this.model = this.transform.GetChild(0).gameObject;
        }
        this.model.transform.localPosition = Vector3.zero;
 
        if (agent == null)
        {
            this.agent = this.gameObject.AddComponent<NavMeshAgent>();
        }
        if (animator == null)
        {
            this.animator = this.gameObject.GetComponentInChildren<Animator>();
        }
        if (boxCollider == null)
        {
            this.boxCollider = this.gameObject.AddComponent<BoxCollider>();
            this.boxCollider.size = new Vector3(131);
            this.boxCollider.center = new Vector3(01.2f, 1);
            this.boxCollider.isTrigger = true;
        }
        this.gameObject.layer = LayerMask.NameToLayer("Monster"); //레이어를 몬스터로
 
        this.skinnedMeshRenderer = this.gameObject.GetComponentInChildren<SkinnedMeshRenderer>();
        this.defaultMaterial = this.skinnedMeshRenderer.material;
 
        this.CheckHp();
    }
    #endregion
 
    #region CHANGEBEHAVIOR
    public void ChangeBehavior(eMonsterState state)
    {
        SetNavAgentEnable(false);
 
        switch (state)
        {
 
            case eMonsterState.MOVE:
                {
                    Move();
                }
                break;
            case eMonsterState.FOLLOW:
                {
                    Follow();
                }
                break;
            case eMonsterState.ATTACK:
                {
                    Attack();
                }
                break;
            case eMonsterState.DIE:
                {
                    Die();
                }
                break;
            case eMonsterState.KNOCKBACK:
                {
                    KnockBack();
                }
                break;
            default:
                break;
        }
    }
    #endregion
 
    #region MOVE
    // 몬스터가 이동하는 매서드 (NavMesh로)
    private void Move()
    {
        if (coBehavior != null)
        {
            StopCoroutine(coBehavior);
        }
        coBehavior = StartCoroutine(MoveImpl());
    }
    IEnumerator MoveImpl() // 목표지점으로 이동하면서 목표지점에 도달하면 앞으로이동
    {
        SetNavAgentEnable(true);
        SetNavAgentDatas();
        switch ((eMonsterType)data.attackType)
        {
            case (eMonsterType.RunTwoAttack):
                {
                    this.animator.Play("Monster_Run");
                }
                break;
            case (eMonsterType.WalkOneAttack):
                {
                    this.animator.Play("Monster_Walk");
                }
                break;
            case (eMonsterType.CrawlBiting):
                {
                    this.animator.Play("Monster_Crawl");
                }
                break;
        }
        while (true)
        {
            if (!agent.pathPending)
            {
                if (agent.remainingDistance <= agent.stoppingDistance)
                {
                    OnCompleteMove();
                    break;
                }
            }
            yield return null;
        }
    }
    #endregion
 
    #region FOLLOW
 
    private void Follow()  //펜스로 전진(-z방향)
    {
        if (coBehavior != null)
        {
            StopCoroutine(coBehavior);
        }
        coBehavior = StartCoroutine(FollowImpl());
    }
    IEnumerator FollowImpl()
    {
        switch ((eMonsterType)data.attackType)
        {
            case (eMonsterType.RunTwoAttack):
                {
                    this.animator.Play("Monster_Run");
                }
                break;
            case (eMonsterType.WalkOneAttack):
                {
                    this.animator.Play("Monster_Walk");
                }
                break;
            case (eMonsterType.CrawlBiting):
                {
                    this.animator.Play("Monster_Crawl");
                }
                break;
        }
        while (true)
        {
            yield return null;
 
            this.gameObject.transform.position += Vector3.back * data.moveSpeed * Time.deltaTime;
 
            this.gameObject.transform.rotation = Quaternion.Euler(01800);
        }
    }
    #endregion
 
    #region ATTACK
    private void Attack()
    {
        if (coBehavior != null)
        {
            StopCoroutine(coBehavior);
        }
        coBehavior = StartCoroutine(AttackImpl());
    }
    IEnumerator AttackImpl()
    {
        while (true)
        {
            switch ((eMonsterType)data.attackType)
            {
                case (eMonsterType.RunTwoAttack):
                    {
                        this.animator.Play("Monster_TwoAttack");
                    }
                    break;
                case (eMonsterType.WalkOneAttack):
                    {
                        this.animator.Play("Monster_OneAttack");
                    }
                    break;
                case (eMonsterType.CrawlBiting):
                    {
                        this.animator.Play("Monster_Biting");
                    }
                    break;
            }
 
            //몬스터의 공격속도에 따라 다른 타이밍을 적용해보자
            yield return new WaitForSeconds(3f);
        }
    }
    #endregion //공격
 
    #region DIE
    private void Die()
    {
        if (coBehavior != null)
        {
            StopCoroutine(coBehavior);
        }
        coBehavior = StartCoroutine(DieImpl());
    }
    IEnumerator DieImpl()
    {
        this.skinnedMeshRenderer.material = defaultMaterial;
 
        //타입에 따라 다르게 몬스터를 죽도록 해본다
        this.animator.Play("Monster_Die1");
        OnMonsterDead();
        yield return new WaitForSeconds(2.9f);
    }
    #endregion
 
    #region KNOCKBACK
    public void KnockBack()
    {
        if (coBehavior != null)
        {
            StopCoroutine(coBehavior);
        }
        coBehavior = StartCoroutine(KnockBackImpl());
    }
    IEnumerator KnockBackImpl()
    {
        for (int i = 0; i < 20; i++)
        {
            this.transform.position += Vector3.forward * 10 * Time.deltaTime;
            yield return null;
        }
    }
    #endregion
 
 
 
    private void SetNavAgentEnable(bool isEnabled)
    {
        this.agent.enabled = isEnabled;
    }
    private void SetNavAgentDatas()
    {
        this.agent.destination = navDestination;
        this.agent.speed = data.moveSpeed;
        this.agent.stoppingDistance = 2f;
    }
 
    private void CheckHp()
    {
        coCheckHp = StartCoroutine(CheckHpImpl());
    }
    IEnumerator CheckHpImpl()
    {
        while (true)
        {
            yield return null;
            if (this.hp <= 0)
            {
                this.OnMonsterDie();
            }
        }
    }
 
    #region HIT
    public void Hit(float damage)
    {
        if (this.hp > 0)
        {
            this.hp -= damage;
            if (coHit != null)
            {
                StopCoroutine(coHit);
            }
            coHit = StartCoroutine(HitImpl());
        }
    }
    IEnumerator HitImpl()
    {
        //메시를 하얗게 바꿔봄
        skinnedMeshRenderer.material = whiteMaterial;
        yield return new WaitForSeconds(0.2f);
        skinnedMeshRenderer.material = defaultMaterial;
    }
    #endregion    
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 
: