c# - 检查角色是否正在下降
问题描述
我制作了这个脚本来检查角色是否正在坠落(我需要它来设置坠落动画),但它仅在它从非常高的高度坠落时才有效。如果我在角色坠落时跳跃,则不会打印“fallen”,而当我从更远的距离开始坠落时会激活它。谁能帮助我或指出另一种方法来检查它是否正在下降?
void Update()
{
float previousHeight = 0f;
var currentHeight = Controller.velocity.y;
if(Controller.isGrounded) currentHeight = 0f;
if(currentHeight < previousHeight) print("fallen");
previousHeight = currentHeight;
}
解决方案
首先在
float previousHeight = 0f;
你一直在创造一个新float
的价值0
......所以对它进行任何检查并最终为它存储一个值是非常没用的。
我怀疑你宁愿已经有一些领域,但不小心掩盖了它。应该是
// Renamed it to make my point below clear
private float previousVelocity;
private void Update()
{
var currentVelocity = Controller.velocity.y;
if(Controller.isGrounded) currentVelocity = 0f;
if(currentVelocity < previousVelocity) print("fallen");
previousVelocity = currentVelocity;
}
现在看这个你会注意到它仍然没有多大意义。我重命名了变量以明确我的观点:您正在检查以前的速度是否小于当前速度。这意味着只有你放慢了速度,不一定是你在跌倒。
您要么更愿意存储和比较绝对位置,例如
private float previousHeight;
private void Update()
{
var currentHeight = Controller.transform.position.y;
if(currentHeight < previousHeight) print("fallen");
previousHeight = transform.position.y;
}
或者你也可以简单地直接使用速度
private void Update()
{
var currentVelocity = Controller.velocity.y;
if(Controller.isGrounded) currentVelocity = 0f;
if(currentVelocity < 0f) print("fallen");
}
推荐阅读
- google-apps-script - 如何使用 selectedType 添加单选按钮,并在 code.js 中禁用一个单选按钮
- r - YAML 标头闪亮滑块范围输入
- swift - Pod install 不安装包
- ruby-on-rails - 如何从字符串参数值中检索关联数据
- mongodb - $all 条件中的空值触发 COLLSCAN 而不是 mongo 中的 IXSCAN
- c# - 基于Multi-tenant Asp.net Core网站参数的JWT认证
- c# - 在 Revit 文档中获取 3D 视图的尺寸
- consensus - 如何证明像 multipaxos 这样的共识实现是正确的?
- javascript - 如何使用 .map() 更改二维数组中的值?
- python-2.7 - 如何不杀死python中另一个进程打开的子进程?