59.내일배움캠프 51일차 TIL <Unity 2D 팀프로젝트- MartialGod:Reborn - 0일차> 06/20

정광훈(Unity_9기)·2025년 6월 20일

TIL (Today I Learned)

목록 보기
61/110
post-thumbnail

오늘 작업한 내용

적이 플레이어를 감지하면 따라가도록 하는 작업을
미리 구현했다.

적이 평소에는 패트롤하는 움직임도 구현해야 한다.

낭떠러지를 감지해 적이 움직임을 멈추고 돌아가도록 구현도 해야한다.


<코드>

using UnityEngine;

// 몬스터 추적
// 1. 플레이어 추적
// 2. 낭떠러지 체크 - 적이 ray를 쏴서 적 중심 기준 바라보는 기준 +3 위치에서 

public class EnemyController : BaseController
{
    [SerializeField] private Transform target; // 플레이어 위치

    [SerializeField] private float followRange = 5f; // 플레이어를 따라가는 감지 거리

    protected float DistanceToTarget() // 적과 플레이어의 거리 계산
    {
        if (target == null)
        {
            Debug.Log("참조할 대상 사라짐");
        }

        return Mathf.Abs(transform.position.x - target.position.x);
    }

    protected Vector2 DirectionToTarget() // 플레이어 추적 방향 계산
    {
        if (target == null)
        {
            Debug.Log("참조할 대상 사라짐");
            return Vector2.zero;
        }

        // 플레이어와 적의 x축 거리만 계산
        float xDistance = target.position.x - transform.position.x;

        Vector2 direction;

        if (Mathf.Abs(xDistance) <= 1.1f) // x축 거리가 1보다 작거나 같을 때
        {
            direction = Vector2.zero; // 정지
        }
        else if (xDistance > 0) // x축 거리가 0보다 클 때 
        {
            direction = Vector2.right; // 오른쪽으로 이동
        }
        else // x축 거리가 0보다 작거나 같을 때
        {
            direction = Vector2.left; // 왼쪽으로 이동
        }

        return direction;
    }

    protected override void MoveToTarget() // 플레이어 추적
    {
        base.MoveToTarget();

        if (target == null)
        {
            Debug.Log("참조할 대상 사라짐");
            return;
        }

        float distance = DistanceToTarget();
        Vector2 direction = DirectionToTarget();

        if (distance <= followRange) // 적이 추적 범위 내에 있다면
        {
            lookDirection = direction; // 바라보는 방향
            movementDirection = direction; // 움직이는 방향
        }
        else // 범위 밖이면
        {
            movementDirection = Vector2.zero; // 정지
        }
    }
}
using UnityEngine;

public class BaseController : MonoBehaviour
{
    protected Rigidbody2D _rigidbody;

    protected Vector2 movementDirection = Vector2.zero; // 이동하는 방향 초기화

    public Vector2 MovementDirection // 외부에서 이동 방향을 읽을 때 사용
    {
        get { return movementDirection; }
    } 

    protected Vector2 lookDirection = Vector2.zero; // 바라보는 방향 초기화

    public Vector2 LookDirection // 외부에서 바라보는 방향을 읽을 때 사용
    {
        get { return lookDirection; }
    } 

    [Header("테스트용 이동속도")] [SerializeField] private float moveSpeed = 5f; // 적 이동속도

    protected virtual void Awake()
    {
        _rigidbody = GetComponent<Rigidbody2D>();
    }

    protected virtual void Update()
    {
        MoveToTarget();
    }

    protected virtual void FixedUpdate()
    {
        Movement(movementDirection);
    }

    protected virtual void MoveToTarget() // 플레이어 추적
    {
    }

    private void Movement(Vector2 direction) // 이동
    {
        _rigidbody.velocity = direction * moveSpeed;
    }
}

0개의 댓글