Unity2D

Unity) [유니티 2D] Physics2D를 활용한 스킬 범위공격 구현

HSH12345 2023. 4. 11. 01:45
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SubmachineGunSkill_03 : Skill
{
    protected override void Start()
    {
        this.isCircle = true;
        this.existTime = 0.783f;
        if (GameObject.Find("PlayerShell").transform.position.x - this.transform.position.x < 0)
            this.GetComponent<SpriteRenderer>().flipX = true;
        base.Start();
    }

    private void Update()
    {
        Collider2D[] colliders = Physics2D.OverlapBoxAll(this.transform.position + new Vector3(1, -0.5f), new Vector2(6, 3), 0);

        foreach (Collider2D collider in colliders)
        {
            if (collider.CompareTag("Monster"))
            {
                Monster monster = collider.GetComponent<Monster>();

                if (monster != null && monster.GetComponent<Rigidbody2D>() != null)
                {
                    Vector2 dir = collider.transform.position - this.transform.position;

                    monster.GetComponent<Rigidbody2D>().AddForce(dir.normalized * this.knockbackSpeed, ForceMode2D.Impulse);
                }

                if (!monster.isSkilldDamaged) 
                {
                    monster.TakeDamage(this.damage);
                    StartCoroutine(monster.SkillDamagedRoutine(this.existTime));
                }

            }
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawCube(this.transform.position + new Vector3(1, -0.5f), new Vector2(6, 3));
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Monster : MonoBehaviour
{
    private int hp = 500;
    public bool isSkilldDamaged;

    void Start()
    {
        
    }

    public void TakeDamage(int damage)
    {
        this.hp -= damage;
        Debug.Log(this.hp);
    }

    public IEnumerator SkillDamagedRoutine(float skillTime)
    {
        this.isSkilldDamaged = true;
        yield return new WaitForSeconds(skillTime);
        this.isSkilldDamaged = false;
    }
}

공격범위를 Gizmo로 나타낸 모습

 

스킬의 컴포넌트에 RigidBody를 추가하지 않고 몬스터에게 있는 Collider를 감지하여 스킬 데미지를 주고 넉백 효과를 주도록 기능 구현했습니다. 이 때 데미지가 중복되지 않도록 코루틴을 사용하였고(코루틴의 인자를 통해 원하는 딜레이 마다 데미지를 줄 수 있음) 넉백에 효과는 기존 몬스터 이동 관련 스크립트에 적용 할 수 있도록 수정해야 합니다.