아카이브

HeroShooter 적이 플레이어 추적 본문

유니티 심화

HeroShooter 적이 플레이어 추적

timbercat 2023. 8. 29. 18:27

플레이어

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

public class Player2 : MonoBehaviour
{
    [SerializeField]
    private float moveSpeed = 2f;

    [SerializeField]
    public float turnSpeed = 50.0f;

    private Rigidbody rBody;

    private Animator anim;

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

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

        if (dir != Vector3.zero)     
        {
            //이동 
            this.transform.Translate(dir * this.moveSpeed * Time.deltaTime);

            //회전
            this.transform.Rotate(Vector3.up * r * Time.deltaTime * this.turnSpeed);

            this.anim.SetInteger("State", 1);
        }
        else
            this.anim.SetInteger("State", 0);
    }
}

몬스터

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

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

    private NavMeshAgent agent;

    // Start is called before the first frame update
    void Start()
    {
        this.agent = this.GetComponent<NavMeshAgent>();
        this.StartCoroutine(this.CoDetectTarget());
    }

    private IEnumerator CoDetectTarget()
    {
        while (true)
        {
            this.agent.SetDestination(this.target.position);
            yield return new WaitForSeconds(0.3f);
        }
    }