模数与协程中的浮点数

时间:2014-01-26 16:59:14

标签: c# math unity3d

我试图做一个coroutine,将角色设置为伤害模式的persiod。在此期间,我希望它闪现。我不熟悉模数,但我试图用它来每10个左右的周期翻转精灵渲染器。但是我得到了非常奇怪的价值,它是否会引起它的浮动?我应该如何团结一致?

public IEnumerator Hurt_cr (float sec, Vector2 attackPosition, float force)
        {
                isHurt = true;

                AddForceAtPosition (attackPosition, force);

                SpriteRenderer sprite = GetComponent< SpriteRenderer> ();
                float t = Time.deltaTime;

                while (t < sec) {

                        if ((t % 10) == 0) {

                                print ("sprite on :  " + sprite.enabled);
                                sprite.enabled = !sprite.enabled;
                        }

                        yield return null;
                        t += Time.deltaTime;
                }

                isHurt = false;
        }

1 个答案:

答案 0 :(得分:-1)

不要使用协同程序,它完全没用。把它放到更新:

sprite.enabled = ((int)(Time.time / 10)) % 2 == 0;

编辑:添加(int)强制转换。

编辑2:让它闪烁固定次数

添加课程属性:

public int flashes = 0;
private bool flashingLastFrame = false;

在更新中计算闪烁,如果有的话:

bool flashingNow;

if (flashes > 0)
{
    flashingNow = ((int)(Time.time / 10)) % 2 == 0;

    if (flashingNow != flashingLastFrame)
    {
        flashingLastFrame = flashingNow;
        sprite.enabled = flashingNow;
        flashes--; // forgot this to make it stop
    }
}

让它从外面闪烁3次:

obj.flashes = 6;

或添加便利方法:

public void Flash(int times)
{
    flashes = times * 2;
}

编辑3:超快速闪烁:

if (flashes > 0)
{
    flashingLastFrame = !flashingLastFrame;
    sprite.enabled = flashingLastFrame;
    flashes--;
}
相关问题