적은 4종류
1. 생성 시점에 플레이어 캐릭터의 위치로 직진하는 적
2. 플레이어 캐릭터를 끊임없이 추적하는 적
3. 플레이어 캐릭터와 특정 거리로 가까워지면 주변을 원형으로 도는 적
4. 플레이어 주변에서 랜덤한 위치로 순간 이동하는 적
3번 적의 움직임을 구현하는 과정에서 플레이어 캐릭터 주변을 원형으로 도는 방법에 대해 고민을 많이 하였다.
Range보다 멀리 떨어진 경우에는 플레이어 캐릭터를 향해 다가가고, Range안에 들어올 때 플레이어 주위를 원형으로 돈다(MoveCircle).
플레이어 캐릭터 - 적 오브젝트 벡터(direction)을 기준으로 각도를 계속 증가시키면서 원형으로 돌게 하였다.
public class HoveringEnemyController : EnemyController
{
[SerializeField, Range(1f, 5f)] private float Range;
private float rad;
private bool isRanged = false;
private Vector2 initDirectionInRange;
protected override void Start()
{
base.Start();
}
protected override void FixedUpdate()
{
base.FixedUpdate();
Vector2 direction = DirectionToTarget();
RotateToTarget(direction);
if (!isRanged)
{
float distance = DistanceToTarget();
CallMoveEvent(direction);
if (distance <= Range)
{
isRanged = true;
initDirectionInRange = direction * -1;
}
}
else
{
direction = direction * -1;
float rotZ = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.localRotation = Quaternion.Euler(0, 0, rotZ);
MoveCircle();
}
}
private void MoveCircle()
{
rad += Time.deltaTime * (speed/Range);
float initialRad = Mathf.Atan2(initDirectionInRange.y, initDirectionInRange.x);
float x = Range * Mathf.Cos(rad + initialRad);
float y = Range * Mathf.Sin(rad + initialRad);
transform.position = PlayerTransform.position + new Vector3(x, y);
if (rad >= Mathf.PI * 2) rad = 0;
}
}