首页 > 解决方案 > 检查角色是否正在下降

问题描述

我制作了这个脚本来检查角色是否正在坠落(我需要它来设置坠落动画),但它仅在它从非常高的高度坠落时才有效。如果我在角色坠落时跳跃,则不会打印“fallen”,而当我从更远的距离开始坠落时会激活它。谁能帮助我或指出另一种方法来检查它是否正在下降?

void Update()
{
  float previousHeight = 0f;
  var currentHeight = Controller.velocity.y;
  if(Controller.isGrounded) currentHeight = 0f;
  if(currentHeight < previousHeight) print("fallen");
  previousHeight = currentHeight;
}

标签: c#unity3d

解决方案


首先在

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");
}

推荐阅读