Unity2D
Unity) [유니티 2D] Physics2D를 활용한 애니메이션 범위공격 구현
HSH12345
2023. 4. 12. 01:29
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AssultRifleSkill_03 : Skill
{
public GameObject leftTop;
public GameObject rightBottom;
public GameObject dirFront;
public GameObject dirBackd;
protected override void Start()
{
this.existTime = 0.652f;
this.transform.parent = GameObject.Find("bulletPoint").transform;
base.Start();
}
public void Update()
{
Collider2D[] colliders = Physics2D.OverlapAreaAll(this.leftTop.transform.position, this.rightBottom.transform.position);
foreach (Collider2D collider in colliders)
{
if (collider.CompareTag("Monster"))
{
Monster monster = collider.GetComponent<Monster>();
if (monster != null && monster.GetComponent<Rigidbody2D>() != null)
{
Vector2 dir = this.dirFront.transform.position - this.dirBackd.transform.position;
monster.GetComponent<Rigidbody2D>().AddForce(dir.normalized * this.knockbackSpeed, ForceMode2D.Impulse);
}
if (!monster.isSkilldDamaged)
{
monster.TakeDamage(this.damage, this.existTime);
}
}
}
}
}
현재 진행 중인 프로젝트에서 범위공격을 구현함에 있어서 Collider를 사용하지 않고 구현하는 것을 목표로 하고 있기 떄문에 Physics2D를 활용하여 모든 범위공격을 구현해야했다.
Physics2D.OverlapAreaAll(vector2, vector2) 메서드는 두개의 위치값을 인자로 받아 첫 번째 인자를 왼쪽 위로 설정하고 두번 째 인자를 오른쪽 아래로 지정하여 가상의 사각형을 만들어 사각형 내부의 콜라이더를 탐색할 수 있도록 기능한다. 해당 기능을 사용하여 두 개의 빈 오브젝트를 스프라이트 애니메이션의 범위와 비슷하게 움직이도록 하면 애니메이션의 움직임에 따라 탐색할 수 있는 범위를 실시간으로 변화시킬 수 있고 마찬가지로 애니메이션에 맞게 빈 오브젝트 두 개를 실시간으로 움직이면서 공격의 방향을 설정하여 넉백 방향을 지정해 줄 수 있었다.
해당 기능은 Collider를 사용한 물리작용보다 세밀하게 충돌하도록 할 수 없지만, 오히려 직접 제어 가능한 물리작용을 만들어 낸다는 점에서 실제 게임에서 더욱 자연스러운 움직임을 만들 수 있을 것 같다.
현재 원하는 범위만큼 공격이 가능하며 원하는 방향으로 넉백이 가능한 것을 확인하였다. 기존 넉백 매커니즘에 적용하여 더 자연스러운 전투를 구현할 수 있을 것 같다.