Unity/엔진프로그래밍

0415_좀비슈터 단계별 테스트 _ 좀비가 타겟을 바라보고 이동

minquu 2021. 4. 15. 18:03
반응형

플레이어를 바라 보면서 좀비가 이동하는 것을 테스트 할 것이다.

 

해야 할 것 

1.좀비가 움직일때 transform.Lookat 를 사용하여서 상대를 바라보게 만들게 한다.

2.그 방향으로 좀비 캐릭터가 움직이게 한다.

-------

 

스크립터 생성하기

 

 

 

 

이동할때 필수적으로 나와야하는 것들 

 

★★★★★ 

 

★dis 거리  = 타겟 - 내 위치
★normal 방향 = dis.normalized 하면 방향이나옴

★★이동 = 방향 * 속도 * 시간 // 이게 공식

 

★★★★★

 

 

먼저 코루틴을 활용해서 공식을 만듭니다. 

 

-----

 

위에 코드를 쓰면 로테이션이 제대로 되지 않아서 그쪽으로 움직이지 않습니다.

 

 

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

public class Zombie : MonoBehaviour
{
    public float speed = 1f;
    private Coroutine coroutine;
    public void Start()
    {

    }
    public void Move(Vector3 targetPos)
    {
        this.transform.LookAt(targetPos);
        if (this.coroutine != null) StopCoroutine(this.coroutine);
        this.coroutine = StartCoroutine(this.MoveImpl(targetPos));
    }
    private IEnumerator MoveImpl(Vector3 targetPos) {
        while (true) {
            var dis = targetPos - this.transform.position; //거리 =  구하는 것은 타겟 - 내오브젝트의 위치
            var normal = dis.normalized;  // 방향은 = 거리. 노멀라이드즈
            this.transform.Translate(Vector3.forward * this.speed * Time.deltaTime);
            yield return null;
        }
    }
}

 

 

  public void Move(Vector3 targetPos)
    {
        this.transform.LookAt(targetPos);
        if (this.coroutine != null) StopCoroutine(this.coroutine);
        this.coroutine = StartCoroutine(this.MoveImpl(targetPos));
    }

코루틴에 처음 진입할때, LookAt으로 타겟을 바라보게 만들어 줍니다.

 

그리고 코루틴이 만약에 존재한다면, 기존에 있던 코루틴을 멈추고, 새로운 코루틴을 실시합니다.

 

targetPos 는 목표로하는 유닛의 포지션 값임

 

  private IEnumerator MoveImpl(Vector3 targetPos) {
        while (true) {
            //var dis = targetPos - this.transform.position; //거리 =  구하는 것은 타겟 - 내오브젝트의 위치
            //var normal = dis.normalized;  // 방향은 = 거리. 노멀라이드즈
            this.transform.Translate(Vector3.forward * this.speed * Time.deltaTime);
            yield return null;
        }
    }

그리고 현재 트랜스레이트 값을 지금 유닛이 바라보고있는 forward 값을 방향으로 잡고, 속도와 시간으로 이동합니다. 

 

 

 

==

앱을 만들어서 그곳에서 메서드를 소환해서 실시한다

 

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

public class App : MonoBehaviour
{
    public PlayerState player;
    public Zombie zombie;

    public void Start()
    {
        this.zombie.Move(player.transform.position);
    }

}

 

 

---

 

 

 

 

반응형