Unity Lerp实现近似匀速过渡固定步长,而非由快到慢的当前比值

思路:

Lerp函数以Vector3为例:

Vector3.Lerp(Pos1,Pos2,LerpStep)

Pos1=起始位置(一般是transform.positon,即每一帧物体的实时位置;对于UI物体则是RectTransform,如下)

Pos2=结束位置

LerpStep=每次调用Lerp函数完成的比例

举个例子:

我把物体放在(0,0,0)

Vector3.Lerp(transform.position,new Vector3(10,0,0),0.1f)

当第一次调用此函数时,物体X坐标为:0+(10-0)*0.1=1

第一次的位置变成(1,0,0)

第二次:(1+(10-1)*0.1,0,0)=(1.9,0,0)

第三次:(1.9+(10-1.9)*0.1,0,0)=(2.71,0,0)

因此,要实现匀速,需要根据进程改变步长

依然以上面这个例子为例,实现匀速:

t= 10/(10-transform.position.x)*0.1;//t=总路程/(总路程-现在路程)*步长

Vector3.Lerp(transform.position,new Vector3(10,0,0),t)

当第一次调用此函数时,t=1*0.1,物体X坐标为:0+(10-0)*0.1=1

第一次的位置变成(1,0,0)

第二次,t=10/(10-1)*0.1=(10/9)*0.1,物体X坐标为:1+(10-1)*(10/9)*0.1=2

第二次位置变成(2,0,0)

第三次:t=10/(10-2)*0.1=(10/8)*0.1,物体X坐标为:2+(10-2)*(10/8)*0.1=3

依次类推(个人想法,不一定对)

下面是个人实现UI移动的代码:

public class ReadBook : MonoBehaviour
{
    public RectTransform Page1;
    public TMPro.TextMeshProUGUI Page1Text;
    public RectTransform Page2;
    public TMPro.TextMeshProUGUI Page2Text;

    private bool isLerp;

    float t;
    float OriginalLength;
    float currentLength;
    public float LerpStep=0.1f;//每次完成10%,乘以Time.deltaTime之后,即总需完成时间=1/0.1=10秒

    public RectTransform LastPage;


    // Start is called before the first frame update
    void Start()
    {
        OriginalLength = (Page2.localPosition - LastPage.localPosition).magnitude;
        Debug.Log("原长为:" + OriginalLength);
    }

    // Update is called once per frame
    void Update()
    {

        if (isLerp)
        {
            
            t = OriginalLength / currentLength * LerpStep*Time.deltaTime;

            Page2.localPosition = Vector3.Lerp(Page2.localPosition, LastPage.localPosition, t);


            if (Page2.localPosition== LastPage.localPosition)
            {

                Debug.Log("Lerp位置已结束");
                isLerp = false;
            }
       
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值