본문 바로가기
KDT/유니티 심화

23/08/29 TestAreaMask

by 잰쟁 2023. 8. 29.
728x90

TestMonster

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.AI;

public class TestMonster : MonoBehaviour
{
    [SerializeField]
    private Transform target;
    private NavMeshAgent agent;
    private Animator anim;

    void Start()
    {
        this.agent = this.GetComponent<NavMeshAgent>();
        this.anim = this.GetComponent<Animator>();
        //코루틴 실행
        this.StartCoroutine(this.CoDetectTarget());
    }

    //목표 지점(타겟 위치)까지 이동하는 코루틴
    IEnumerator CoDetectTarget()
    {
        while (true)
        {
            //목표 지점(타겟 위치) 설정
            this.agent.SetDestination(this.target.position);
            //0.3초마다 갱신
            yield return new WaitForSeconds(1f);
        }
    }

    private void OnTriggerEnter(Collider other)
    {
        this.anim.SetTrigger("Attack");
    }
}

TestPlayer

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestPlayer : MonoBehaviour
{
    [SerializeField]
    private float speed = 10;
    private Animator anim;

    // Start is called before the first frame update
    void Start()
    {
        this.anim = this.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        float h = Input.GetAxisRaw("Horizontal");
        float v = Input.GetAxisRaw("Vertical");
        Vector3 dir = new Vector3(h, 0, v);

        if (dir != Vector3.zero)
        {
            this.anim.SetInteger("State", 1);
            //회전할 각도
            var angle = Mathf.Atan2(dir.x,dir.z) * Mathf.Rad2Deg;
            //Y축을 기준으로 회전하기
            this.transform.rotation = Quaternion.AngleAxis(angle, Vector3.up);
            //이동하기
            this.transform.Translate(Vector3.forward * this.speed * Time.deltaTime);
        }
        else 
        {
            this.anim.SetInteger("State", 0);
        }
    }
}