unity3d - 如何在 Unity 中使用 Lerp Dash 运动
问题描述
我正在 Unity 中做一个初学者项目,并想使用 Vector3.Lerp 为破折号运动做动画。这是我的代码,我正在努力找出它为什么不起作用。
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
Vector3 start = transform.position;
Vector3 dash = new Vector3(start.x + m_DashDist, start.y);
transform.position = Vector3.Lerp(start, dash, Time.deltaTime);
}
}
解决方案
Lerp
工作原理
您传递给Lerp
函数的最后一个参数是一个浮点值(主要在0f
和之间1f
)。
- 如果此值为
0f
,Lerp
将返回第一个参数(假设为_dashStart
)。 - 如果此值为
1f
,Lerp
将返回第二个参数(假设为_dashEnd
)。 - 如果此值为
0.5f
,Lerp
将返回第一个和第二个参数之间的“中间值”。
如您所见,此函数根据第三个参数在这两个参数之间进行插值。
Time.deltaTime
必须每帧调用此函数,并且在您的情况下,浮点值(第三个参数)需要每帧递增。
但是你的 if 块只执行一次,当你按下时E
。例如,您可以在按键被按下bool
时将 a 设置为 true 。E
这是进一步的代码——希望没有错误:
public float dashTime = 0.1f;
private float _currentDashTime = 0f;
private bool _isDashing = false;
private Vector3 _dashStart, _dashEnd;
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if (_isDashing == false)
{
// dash starts
_isDashing = true;
_currentDashTime = 0;
_dashStart = transform.position;
_dashEnd = new Vector3(_dashStart.x + m_DashDist, _dashStart.y);
}
}
if (_isDashing)
{
// incrementing time
_currentDashTime += Time.deltaTime;
// a value between 0 and 1
float perc = Mathf.Clamp01(_currentDashTime / dashTime);
// updating position
transform.position = Vector3.Lerp(_dashStart, _dashEnd, perc);
if (_currentDashTime >= dashTime)
{
// dash finished
_isDashing = false;
transform.position = _dashEnd;
}
}
}
有不同的使用方法Lerp
。我主要使用这种方法。
推荐阅读
- python - 如何在 Python 中的二维数组中输入随机生成的整数值
- pusher - 有没有办法通过 API 调用创建 Pusher App?
- vim - 使用 :g 搜索不使用 PyCharm IdeaVIM 插件
- c++ - 这是什么构造:模板
无效函数名称(int i)? - python - 如何找到图像的填充大小?
- vue.js - Vue3在单个文件组件中的元素上存在css类在添加到dom时导致渲染失败,无效的VNode类型:Symbol()
- excel - 有没有办法使用 isnumber 和 search 从多个单元格中提取并搜索多个单元格以返回多个单元格?
- python - 用python脚本打开python脚本
- javascript - Hello World 页面上的 Safari 内容安全策略错误
- reactjs - 编辑在确认电子邮件 dj_rest_auth 中发送的 url