简体   繁体   English

如何检查2d统一的垂直速度?

[英]How to check for vertical velocity in 2d unity?

I am trying to animate my sprite when my vertical velocity is less than 0 (moving downwards). 当我的垂直速度小于0(向下移动)时,我试图为我的精灵设置动画。 How do you do it? 你怎么做呢?

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

Try to change VERTICALVELOCITY and maybe help with the code. 尝试更改VERTICALVELOCITY并可能有助于代码。 Also, should I do it in Void Update or FixedUpdate? 另外,我应该在Void Update还是FixedUpdate中进行此操作?

If you're using a rigibody you may do this: 如果您正在使用rigibody,您可以这样做:

public class CheckSpeed : MonoBehaviour
{
    private Rigidbody2D rb2D;

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

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

Your code will become: 您的代码将变为:

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

Since this is related to an animation I would set it to LateUpdate. 由于这与动画有关,我将其设置为LateUpdate。

Do you have a rigidbody on that gameobject? 那个游戏对象上有一个僵硬的人吗? Then it's easy. 那很容易。

private Rigidbody rb;

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

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

Otherwise, you need to log the y-position every frame. 否则,您需要每帧记录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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM