c# - 将对象平滑移动到目标 Unity3D
问题描述
我一整天都在尝试将一个物体从A点平稳地移动到B 点,所以我尝试了Lerp、MoveTowards和SmoothDamp但每次物体从 A 点消失并立即出现在 B 点!
我尝试了在互联网上找到的所有解决方案,但得到了相同的结果。
你能救我的命并帮我解决这个问题吗?
这是我尝试过的代码:
transform.position = Vector3.SmoothDamp(transform.localPosition, Destination, ref velocity, Speed);
transform.position = Vector3.Lerp(transform.localPosition, Destination, Speed);
transform.position = Vector3.MoveTowards(transform.localPosition, Destination, Speed);
和更多...
解决方案
您需要使用 Lerp 不断更新位置。您可以使用协程执行此操作,如下所示(假设 Origin 和 Destination 是已定义的位置):
public IEnumerator moveObject() {
float totalMovementTime = 5f; //the amount of time you want the movement to take
float currentMovementTime = 0f;//The amount of time that has passed
while (Vector3.Distance(transform.localPosition, Destination) > 0) {
currentMovementTime += Time.deltaTime;
transform.localPosition = Vector3.Lerp(Origin, Destination, currentMovementTime / totalMovementTime);
yield return null;
}
}
你可以调用这个协程:
StartCoroutine(moveObject());
推荐阅读
- java - Java Spring API - continous status
- amazon-web-services - Amazon S3 - 前缀可以包含文件名的开头吗?
- android - 如何用字符串制作 IntTween 动画?
- javascript - Vue JS 仪表板模板未在浏览器中正确加载
- css - Material Design vs Bootstrap React、Angular、Vue 实现
- github-actions - GitActions 作业名称基于矩阵索引而不是矩阵值
- f# - 具有 3 个参数的 F# 自定义运算符
- python - 自动调整列宽以适应熊猫生成的 Excel 文件中的内容
- node.js - 从 Angular 项目创建一个 docker 容器
- powerbi - Power BI 计算具有多个 ALL 条件的度量以绕过切片器