본문 바로가기

Project/전투 시스템

[전투 시스템] Unity: 적 컨트롤러 만들기 (2)

728x90

코루틴을 사용한 적 움직임 구현입니다.

 

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
  IEnumerator EnemyControl()
    {
        while (true)
        {
            float x = transform.position.x + Random.Range(-1f, 1f);
            float y = transform.position.y + Random.Range(-1f, 1f);
 
            Vector2 target = new Vector2(x, y);
            target = CheckTarget(target);
            prevPosition = transform.position;
 
            if(!(target.x < prevPosition.x))
            {
                Vector3 scale = transform.localScale;
                scale.x = -Mathf.Abs(scale.x);
                transform.localScale = scale;
            }
            else
            {
                Vector3 scale = transform.localScale;
                scale.x = Mathf.Abs(scale.x);
                transform.localScale = scale;
            }
 
            if (Time.time > nextAttackTime)
            {
                Attack();
                nextAttackTime = Time.time + attackReload;
 
                yield return new WaitForSeconds(attackReload);
            }
 
            while (Vector2.Distance(transform.position, target) > 0.001f)
            {
                animator.SetBool("isMove"true);
                transform.position = Vector2.MoveTowards(transform.position, target, moveSpeed);
                yield return null;
            }
            animator.SetBool("isMove"false);
 
            float randomIdleTime = Random.Range(0.5f, 1f);
 
            yield return new WaitForSeconds(randomIdleTime);
        }
    }
}

 

  • 5행 ~ 10행 - 적이 움직일 다음 위치를 계산하는 부분입니다.
  • 12행 ~ 23행 - 적의 움직임에 따라 적을 뒤집어주는 부분입니다.
  • 25행 ~ 31행 - 공격 가능한 시간이 되면 적의 공격을 구현시켜주는 부분입니다.
  • 33행 ~ 39행 - 계산된 다음 위치로 적을 움직여 주는 부분입니다.
  • 41행~ 43행 - 코루틴의 마지막 부분으로 잠깐의 휴면상태를 가집니다.

 

728x90