K-digital traning/유니티 심화

캐릭터 이동 후 normal(법선벡터)로 회전

내꺼블로그 2023. 8. 21. 12:47
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestPlayer : MonoBehaviour
{
    [SerializeField]
    private Transform sight;
    private Quaternion rot;
    private Vector3 targetTrans;
    public float damping = 10f;
    public void Move()
    {
        Ray ray = new Ray(this.sight.position, this.transform.forward);
        Debug.DrawRay(ray.origin, ray.direction * 100f, Color.yellow, 5f);
        RaycastHit hit;
        if (Physics.Raycast(ray, out hit, 100f))
        {
            DrawArrow.ForDebug(hit.point, hit.normal, 5f, Color.green, ArrowType.Solid);
            Debug.Log(hit.normal);
            rot = Quaternion.LookRotation(hit.normal);
            this.targetTrans = Vector3.forward * hit.point.z + Vector3.right * hit.point.x;
            this.transform.LookAt(this.targetTrans);
            StartCoroutine(Comove(hit.normal));
        }
    }

    private IEnumerator Comove(Vector3 vector)
    {
        while (true)
        {
            float dis = Vector3.Distance(this.transform.position, this.targetTrans);
            if (dis < 0.2f)
                break;
            this.transform.Translate(Vector3.forward * Time.deltaTime);
            yield return null;
        }
        while (true)
        {
            if (this.transform.forward == vector)
                break;
            this.transform.rotation = Quaternion.Slerp(this.transform.rotation, rot, Time.deltaTime * damping);
            Debug.Log(this.transform.rotation);
            yield return null;
        }
    }
}