旋转值之间的 lerping 导致游戏对象的位置变化

问题描述

情况

在我的游戏中,我有一艘船,它跟随我的手指在屏幕上的任何位置(或带有光线投射的鼠标,仅用于测试)。我不想为运动或物理使用动画,因为我想实现什么(动画对于船的运动感觉不太好,而物理对于我正在做的事情来说太复杂了)。

这是我的移动和旋转控件:

 if (Input.GetMouseButton(0))
    {
        
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray,out hit,Mathf.Infinity,layerMask))
       {
            
            Vector3 target = hit.point;
            transform.position = Vector3.Movetowards(transform.position,new Vector3(target.x,transform.position.y,target.z),speed);

            if(target.x - transform.position.x > 0)
            {
                right = true;
                isIdle = false;
            }
            else
            {
                right = false;
                isIdle = false;
            }
        }
    }
    else
    {
        isIdle = true;
        
        if (transform.rotation == originalRotation)
        {
            restoreRotation = false;
        }
        else
        {
            restoreRotation = true;
        }

        if (restoreRotation)
        {
            transform.rotation = Quaternion.Lerp(transform.rotation,originalRotation,Time.deltaTime * 5);
        }

这就是为什么我添加3个协程一个用于空闲旋转,一个用于向右旋转,一个向左旋转。比如这是右移的协程:

IEnumerator rightAnimation(float time)
{
    while (true)
    {

        if (right == true && isIdle == false)
        {
            float elapsedtime = 0;

            if (transform.rotation != Quaternion.Euler(-2,13,-8))
            {

                while (elapsedtime < time)
                {
                    transform.rotation = Quaternion.Lerp(transform.rotation,Quaternion.Euler(-2,-8),(elapsedtime / time));
                    elapsedtime += Time.deltaTime;

                    yield return null;
                }
            }

            elapsedtime = 0;

            while (elapsedtime < time)
            {
                transform.rotation = Quaternion.Lerp(Quaternion.Euler(-2,Quaternion.Euler(-7,(elapsedtime / time));
                elapsedtime += Time.deltaTime;

                yield return null;
            }

            elapsedtime = 0;

            while (elapsedtime < time)
            {
                transform.rotation = Quaternion.Lerp(Quaternion.Euler(-7,(elapsedtime / time));
                elapsedtime += Time.deltaTime;

                yield return null;
            }
        }

        yield return new WaitForSeconds(0.1f);
    }

如果 right == true 则我的协程检查轮换并且 lerp 到新的轮换。我检查了检查器上的值,看起来不错,就像这样:

没有位置变化,这是完美的,因为位置由非常简单的 Movetowards 控制。

当我在游戏中尝试我的代码时,协程工作正常并且它们以正确的方式循环,但发生了这种情况:

我的相机无法跟随船的中心,没有动画也很好,船比我的手指向右移动了一点,有时它甚至破坏了协程,因为如果我继续拖动手指到在右侧,看起来我仍在船上,但 Unity 认为我正在向左移动,因此它会快速更改动画并向左移动 2-3 个单位,就像传送一样。

我一开始以为是枢轴的问题,但船实际上只是一个空的游戏对象,在船的模型内,并且全部居中:

我不知道,我没有以任何方式在轮换之间用那个 Lerp 改变位置,所以我对此一无所知

解决方法

你没有通过代码让相机跟随船?

如果我是对的,只需添加一个脚本使相机跟随船,一切都应该正常......我猜

,

我实际上通过移除电影机解决了这个问题,基本上,它造成了这些问题:

  1. 它随着船的旋转而产生奇怪的视角
  2. 旋转的变化正在改变光线投射的方向,导致船快速改变并出现故障

有了新的相机和我制作的代码,它现在就像一个魅力!