유니티 심화

절대강좌 유니티 - 내비게이션 고급 기법, 동적장애물, 적 자연스러운 회전처리, Area Mask

다모아 2023. 8. 29. 12:45

NavMeshObstacle 컴포넌트 - 동적장애물

 

Carve = 우회해서 돌아옴

 

자연스러운 회전처리

Agent의 Auto Update 비활성화

 


RotateEnemy

 

StoppingDistance에 거의 맞게 움직이기

Acceleration은 감속하거나 증가해서 미끄러짐

using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using UnityEngine.AI;
using UnityEngine;
using Vector3 = UnityEngine.Vector3;
using Quaternion = UnityEngine.Quaternion;

public class TestMonster : MonoBehaviour
{
    [SerializeField]
    private Transform target;

    private NavMeshAgent agent;
    
    private float speed = 3f;

    [SerializeField]
    private float damping = 5f;
    private void Awake()
    {
        this.agent = this.GetComponent<NavMeshAgent>();
        //자동회전되지않게 막기
        this.agent.updateRotation = false;
    }

    
    // Start is called before the first frame update
    void Start()
    {
        this.agent.SetDestination(this.target.position);
        
    }

    private void Update()
    {
        if(this.agent.remainingDistance >= this.agent.stoppingDistance)
        {
            //에이전트의 이동방향
            Vector3 dir = this.agent.desiredVelocity;
            DrawArrow.ForDebug(this.transform.position, dir.normalized, 0, Color.red, ArrowType.Solid);
            //회전
            Quaternion rot = Quaternion.LookRotation(dir.normalized);
            //바로바뀜
            //this.transform.rotation = rot;

            //Slerp, 구면 선형보간
            this.transform.rotation = Quaternion.Slerp(this.transform.rotation, rot, Time.deltaTime * this.damping);
        }
        //var dir = this.target.position - this.transform.position;
        //this.agent.velocity = dir.normalized * this.speed;// * Time.deltaTime;
        //var distance = UnityEngine.Vector3.Distance(this.target.transform.position, this.transform.position);
        //Debug.Log(distance);
        //if(distance <= this.agent.stoppingDistance)
        //{
        //    this.agent.velocity = UnityEngine.Vector3.zero;
        //}
        //else
        //{
        //    this.agent.velocity = dir.normalized * this.speed;
        //}
        //Debug.Log(this.agent.velocity);
    }
}