如何检查二维统一的垂直速度?

时间:2019-05-27 13:42:44

标签: c# unity3d

当我的垂直速度小于0(向下移动)时,我试图为我的精灵设置动画。你如何做到的?

if (VERTICALVELOCITY < 0) {
animator.SetFloat("IsFalling", true);
}

尝试更改VERTICALVELOCITY,并可能在代码方面提供帮助。 另外,我应该在Void Update或FixedUpdate中执行此操作吗?

2 个答案:

答案 0 :(得分:0)

如果您使用的是刚体,则可以执行以下操作:

public class CheckSpeed : MonoBehaviour
{
    private Rigidbody2D rb2D;

    void Start() => rb2D = GetComponent<Rigidbody2D>();

    private float GetVerticalSpeed() => rb2D.velocity.y;
}

您的代码将变为:

if (GetVerticalSpeed() < 0) {
animator.SetFloat("IsFalling", true);
}

由于这与动画有关,因此我将其设置为LateUpdate。

答案 1 :(得分:0)

在该游戏对象上您有刚体吗?那很容易。

private Rigidbody rb;

Start()
{
    rb = getComponent<Rigidbody>();
}

Update ()
{
    if(rb.velocity.y < 0)
    {
        // do your stuff
    }
}

否则,您需要每帧记录y位置。

float ypos_lastframe = 0;

Start()
{
    ypos_lastframe = transform.position.y;
}

Update()
{
    if(transform.position.y < ypos_lastframe)
    {
       // do your stuff
    }
    // important to do this assignment AFTER the check above.
    ypos_lastframe = transform.position.y;
}