1. 카메라 고정

 

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

public class MainCamera : MonoBehaviour
{
    public GameObject misaki;
    Coroutine routine;
    // Start is called before the first frame update
    void Start()
    {
        this.routine = this.StartCoroutine(this.FollowMisaki());
    }

    // Update is called once per frame
    IEnumerator FollowMisaki()
    {
        while (true)
        {
            this.transform.position = misaki.transform.position + new Vector3(2f, 2f, 2f);

            yield return null;
        }
    }
}

 

 

2. 미사키

 

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

public class Misaki : MonoBehaviour
{
    Coroutine routine;
    Vector3 dir;
    Vector3 arrivePoint;
    Animator anim;

    // Start is called before the first frame update
    void Start()
    {
        this.routine = this.StartCoroutine(this.Move());
        
        
        //StopCoroutine(this.routine);
    }

    //코루틴
    IEnumerator Move()
    {
        this.anim = this.GetComponent<Animator>();

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

                RaycastHit hit;

                if (Physics.Raycast(ray, out hit, 100f))
                {                
                    this.arrivePoint = hit.point;
                    this.dir = hit.point - this.transform.position;
                }

                Quaternion rot = Quaternion.LookRotation(dir.normalized);
                transform.rotation = rot;
            }

            if (Mathf.Round(this.transform.position.x * 10) != Mathf.Round(this.arrivePoint.x * 10) && Mathf.Round(this.transform.position.z * 10) != Mathf.Round(this.arrivePoint.z * 10))
            {
                this.transform.Translate(dir.normalized * 4f * Time.deltaTime, Space.World);
                this.anim.SetInteger("State", 1);                
            }
            else this.anim.SetInteger("State", 0);

            yield return null;
        }        
    }
}

 

 Quaternion 을 사용하여 3D에서 캐릭터가 원하는 방향을 보도록 설정할 수 있다.

Rotation값을 변경하였다면 캐릭터가 이동할 때 월드좌표를 통해 이동하도록 해야 한다.

'C# > 수업 내용' 카테고리의 다른 글

230202  (0) 2023.02.02
Unity) 바구니 게임  (0) 2023.02.02
230201  (0) 2023.02.01
밤송이  (0) 2023.02.01
메카님 연습 Cs  (0) 2023.02.01

+ Recent posts