Is something wrong with my shake code?

I have this IEnumerator which should shake a transform, and zero out the position when it is finished.
When it is running though it seems to prefer to go left, I wonder if this is me getting bad rolls, or if I am imagining it.

If someone could look at the code and tell me if i’m doing something wrong or if i’m imaging it.

public static IEnumerator Shake(Transform obj, float duration, float magnitude)
    {
        float dur = duration;
        float mag = magnitude;

        while (dur > 0)
        {
            obj.localPosition = Random.insideUnitCircle * mag;
            dur -= Time.deltaTime;
            yield return new WaitForEndOfFrame();
        }

        obj.transform.localPosition = Vector2.zero;
    }

Well, you don’t take the start position into account, so if the start position is (1,0) then it would go to the left of course. But if not, then this should be balanced.

You could test by doing something like:

float cumulativeX = 0f;
for (int x=0;x<100000;x++) {
Vector3 pos = Random.insideUnitSphere;
cumulativeX += pos.x;
}
Debug.Log(cumulativeX / 100000f);

The logged value should be incredibly small, and should not be reliably either positive or negative.

1 Like

Also, you could use Debug.Break() at the beginning of your coroutine and then go frame-by-frame in the editor, to see where the position actually is. It looks like your code would shake the object so fast that it would be hard to see where the actual position is at any one time.

1 Like

Thanks guys, good to know. I think its just a mix of the tiles i’m using to test, and how fast the shake happens.
I only noticed the ‘bug’ when it was a quick few frame shake anyways.
I always forget about the frame by frame in the editor, Its a good way to test all of this out.