最近突然喜欢上游戏起来,然后加入unity 学习队伍,每天学习一丢丢,记录下来,共同进步.
static functionLerp (from : Vector2, to : Vector2, t : float) : Vector2
两个向量之间的线性插值。按照数字t 在 form 到 to 之间插值。 返回是一个 Vector2 坐标
1. 方法解释:
from是起点坐标,to表示终点坐标,t是起点到终点插值,作用范围是(0-1)
函数最终返回值是坐标点 ,采用计算 from +(to-from)* t
2. t 参数取值解释
当 t=0 , Vector3.Lerp( A, B , t ) ---返回结果 A坐标点
当 t=1 , Vector3.Lerp( A, B , t ) ---返回结果 B坐标点
当 0 < t < 1 , Vector3.Lerp( A, B , t ) ---返回结果 就要采用公式: A+(B-A)* t
3. 代码使用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
void Start()
{
Vector2 from = new Vector2(-5f,0);
Vector2 to = new Vector2(5f, 0);
print(Vector2.Lerp(from, to, 0.0f).ToString());
print(Vector2.Lerp(from, to, 0.1f).ToString());
print(Vector2.Lerp(from, to, 0.2f).ToString());
print(Vector2.Lerp(from, to, 0.3f).ToString());
print(Vector2.Lerp(from, to, 0.4f).ToString());
print(Vector2.Lerp(from, to, 0.5f).ToString());
print(Vector2.Lerp(from, to, 0.6f).ToString());
print(Vector2.Lerp(from, to, 0.7f).ToString());
print(Vector2.Lerp(from, to, 0.8f).ToString());
print(Vector2.Lerp(from, to, 0.9f).ToString());
print(Vector2.Lerp(from, to, 1.0f).ToString());
}
}
打印结果
注意start() 方法中, 定义了两个 from. to 坐标,作为起始坐标,根据程序理解是不是应该都懂了,如果还是不清楚,再举个例子
4. 案例结合使用
比如开始 A (0,0) 和 B (100,0) 的距离是100米,t=0.1 ,设置t 固定值,不改变,看看什么效果
Update() 方法,
执行第一帧,结合公式计算, A = A +(100-0)*0.1, A 新位置 (10,0)
A是第一帧移动了10米,即为A往B方向移动了10米,此时A和B距离就剩下90米了
执行第二帧, 结合公式: A = A +(100-10)*0.1 , A 新位置 (19,0)
A是第二帧移动了9米, 即为A往B方向移动了9米,此时A和B距离就剩下81米了
执行第三帧, 结合公式: A = A +(100-19)*0.1 , A 新位置 (27.1,0)
A是第三帧移动了8.1米, 即为A往B方向移动了8.1米,此时A和B距离就剩下72.9米了
同理,后续
我们会发现,这个算法会让A每帧移动的距离都在减少,也就意味着A的速度在逐渐降低。
但是还在往B的方向走,直至终点B。
这个例子更好解释了使用了吧。
作为PY 前端开发者,开始加入Unity 学习,希望不断地进步.