본문 바로가기
Unity/수업과제

[Unity3D] Coroutine 활용 예제

by 왹져박사 2023. 2. 2.
728x90
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Masaki : MonoBehaviour
{
    Coroutine routine;
    Animator anim;
    Rigidbody rbody;
    Vector3 dir;
    Vector3 hitPoint;
    public float walkSpeed = 1.0f;

    void Start()
    {
        anim = this.GetComponent<Animator>();
        rbody = this.GetComponent<Rigidbody>();

        this.routine = StartCoroutine(Move());      //코루틴 함수 시작
    }

    //코루틴 (이벤트 함수)
    IEnumerator Move()
    {
        while (true)
        {
            anim.SetInteger("State", 0);

            if (Input.GetMouseButtonDown(0))
            {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                Debug.DrawRay(ray.origin, ray.direction, Color.red, 2f);

                RaycastHit hit;

                if (Physics.Raycast(ray, out hit, 100f))
                {
                    hitPoint = hit.point;
                    dir = hit.point - this.transform.position;
                    dir.Normalize();
                }
            }
            if ((Int32)this.transform.position.x != (Int32)this.hitPoint.x || (Int32)this.transform.position.z != (Int32)this.hitPoint.z)
            {
                this.transform.rotation = Quaternion.LookRotation(dir);
                this.transform.Translate(dir.normalized * 4f * Time.deltaTime, Space.World);
                this.anim.SetInteger("State", 1);
            }
            else this.anim.SetInteger("State", 0);

            yield return null;      //1프레임 건너뛴다. 끝나지 않음
        }
    }
}

목표 좌표와 현재 좌표를 float로 비교했을 경우, Misaki가 멈추지 않음 : int로 변환

 

 

728x90