Unity2D
Unity) [유니티 2D] A* PathFinder 기반 원거리 적 구현
HSH12345
2023. 3. 10. 04:24
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Pathfinding;
public class AIRangeEnemy : AIEnemy
{
public float attackMoveSpeed;
private float tmpSpeed;
private GameObject scanGo;
public Transform bulletPoint;
public GameObject bulletGo;
public void Start()
{
this.seeker = this.GetComponent<Seeker>();
this.rBody2D = this.GetComponent<Rigidbody2D>();
this.anim = this.GetComponent<Animator>();
this.tmpSpeed = this.speed;
InvokeRepeating("UpdatePath", 0f, this.pathUpdateSeconds);
}
void FixedUpdate()
{
if (this.TargetInDistance() && this.followEnabled) this.PathFollow();
if (this.dist < 5.0f)
{
if(this.scanGo == null) this.RangeAttack();
else
{
if(this.scanGo.tag != "Obstacles") this.RangeAttack();
else this.SetIdle();
}
}
else this.SetIdle();
this.RayCast();
}
private void RangeAttack()
{
this.anim.SetInteger("State", 1);
this.speed = this.attackMoveSpeed;
}
private void SetIdle()
{
this.anim.SetInteger("State", 0);
this.speed = this.tmpSpeed;
}
private void RayCast()
{
Debug.DrawRay(this.rBody2D.position, this.dirPlayer * 5f, new Color(0, 1, 0));
RaycastHit2D rayHit = Physics2D.Raycast(this.rBody2D.position, this.dirPlayer, 5f, LayerMask.GetMask("Obstacles"));
if (rayHit.collider != null)
{
this.scanGo = rayHit.collider.gameObject;
Debug.Log(this.scanGo.name);
}
else this.scanGo = null;
}
public void InstantateBullet()
{
var go = Instantiate(this.bulletGo, this.bulletPoint);
go.GetComponent<EnemyBullet>().Init(this.dirPlayer);
}
}
적오브젝트와 플레이어 오브젝트의 거리를 재서 공격을 하도록 하고, 레이캐스트 기능을 활용하여 플레이어와 적 오브젝트 사이에 장애물을 감지하여 공격을 멈추도록 한다. 현재 플레이어가 장애물에 아주 가깝게 겹쳐있을 때 레이캐스트가 장애물을 먼저 감지하기 때문에 몇몇 상황에서 공격을 하지 못하는 상황이 발생하는데 이 부분을 수정해야한다.