Unity/2D RPG

근접 공격 by Unity

YunSeong 2021. 7. 7. 22:47
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
Rigidbody rigid2D;
Animator animator;
 
public int damage = 5;
 
private float curTime;
public float coolTime = 0.5f; // 공격 쿨타임
 
void Attack() //공격
{
        this.animator.SetTrigger("attacking");
        curTime = coolTime;
        StartCoroutine("Attacking"); //Coroutine for 애니메이션의 타격시간과 실질 데미지가 다는 시간을 동일하게 하기 위해서
    }
}
 
IEnumerator Attacking()
{
    yield return new WaitForSeconds(0.16f);
 
    Vector3 posForThrowingATK = new Vector3(transform.position.x + 0.5f * this.transform.localScale.x / 0.3f, transform.position.y + 0.1f, transform.position.z);
    GameObject go = Instantiate(this.effect, posForThrowingATK, transform.rotation) as GameObject; //effect 소환 -> effect에 닿으면 데미지가 닳음
 
    yield return new WaitForSeconds(0.14f);
}
 
void Start()
{
    this.rigid2D = GetComponent<Rigidbody2D>();
    this.animator = GetComponent<Animator>();
}
 
void Update()
{
    if (Input.GetKeyDown(KeyCode.I)) Attack(); // 공격
 
    if (curTime > 0) curTime -= Time.deltaTime; // 쿨타임
}
 
 
cs

위 코드를 통해서 I키를 인식해서 attack 함수를 호출하도록 했다.

 

그리고 curTime, coolTime을 이용해서 공격을 하는데 시간이 들도록 했다. 

curTime이 coolTime으로 초기화 된다면 0보다 커지기 때문에 매 프레임마다 curTime을 시간의 변화량으로 빼게 되고

curTime이 0보다 작아지면 공격을 할 수 있게 되는 것이다. 만약 공격을 한다면 curTime은 다시 coolTime으로 초기화 된다. 

 

 

 

그리고 여기서 coroutine을 사용한다. coroutine에 대해서 제대로 배우지는 못 했지만 프레임과 다른 시간 단위가 필요한 작업을 할 때 사용하는 것 정도인 것 같다.

 

여기서는 공격하는 animation을 실행시키고 칼이 상대에 맞는 정도로 휘둘러졌을 때 실질적으로 데미지를 넣기 위해서 시간차가 필요했다. 

 

 

 

 

 

그리고 Instantiate를 이용해서 this.effect를 소환하는데 그 effect의 component인 c#파일은 아래와 같다. 

 

1
2
3
4
5
6
7
void OnTriggerEnter2D(Collider2D other)
{
    if (other.tag == "Villain")
    {
        other.GetComponent<villainCommon>().damaged(GameObject.FindWith("Player").GetComponent<PlayerController>().damage);
    }
}
cs

effect에 Collider을 설정하고 Trigger로 만들어주면 collider이 범위에 들어올 때마다 OnTriggerEnter2D 함수가 실행된다. 

그래서 그 collider의 tag에 따라서 대상을 선별하고 그 대상에 damaged(int damage) public함수를 미리 만들어둔다면 

공격을 구현할 수 있다.  effect object를 없애는 것은 Destroy 내장함수를 이용해서 없애면 된다. 

 

그리고 이 effect object를 앞으로 움직이게 한다면 참격 같은 식으로도 활용할 수 있을 것이다. 

728x90
반응형

'Unity > 2D RPG' 카테고리의 다른 글

회복 아이템 by Unity  (0) 2021.07.18
캐릭터(슬라임) by Unity  (0) 2021.07.18
원거리 공격 by Unity  (0) 2021.07.14
카메라 무빙 by Unity  (0) 2021.07.08
유닛 이동 by Unity  (0) 2021.07.07