using System.Collections;
using UnityEngine;

public class TestPlayerSlerp : MonoBehaviour
{
    [SerializeField]
    private Transform eye;
    public float moveSpeed = 5.0f;
    public float rotationSpeed = 2.0f;

    private void Start()
    {
        MoveForward();
    }
    public void MoveForward()
    {
        Ray ray = new Ray(this.eye.position, this.transform.forward);
        RaycastHit hitInfo;

        if (Physics.Raycast(ray, out hitInfo))
        {
            Debug.DrawRay(ray.origin, ray.direction * hitInfo.distance, Color.blue, 5f);
            StartCoroutine(CoMoveForward(hitInfo.distance, hitInfo.normal));
        }
        else
        {
            Debug.DrawRay(ray.origin, ray.direction * 100f, Color.blue, 5f);
        }
    }

    private IEnumerator CoMoveForward(float distance, Vector3 wallNormal)
    {
        float moveAmount = 0;
        while (moveAmount < distance)
        {
            float step = moveSpeed * Time.deltaTime;
            moveAmount += step;
            this.transform.Translate(Vector3.forward * step);

            if (moveAmount > distance)
            {
                float excess = moveAmount - distance;
                this.transform.Translate(Vector3.back * excess);
            }

            yield return null;
        }


        Vector3 reflectDirection = Vector3.Reflect(this.transform.forward, wallNormal);
        Quaternion targetRotation = Quaternion.LookRotation(reflectDirection);
        float t = 0.0f;

        while (t < 1.0f)
        {
            t += Time.deltaTime * rotationSpeed;
            this.transform.rotation = Quaternion.Slerp(this.transform.rotation, targetRotation, t);
            yield return null;
        }
    }
}

반응형

+ Recent posts