A good way to reuse your 'running' state is to do something like this

I changed playerHasHorizontalSpeed to a bool named isRunning and created a check in Update(). That way I can do this check once.

Cleaner code. Gets the same basic left or right movement detection in one go.

I’m sure I’ll update the naming and change this up slightly, but figured people would be interested in one way to check once and then pass into functions without the need to check in every function (and to avoid a class level scoped variable.

void Update()
    {
        bool isRunning = Mathf.Abs(myRigidbody.velocity.x) > Mathf.Epsilon;

        Run(isRunning);
        FlipSprite(isRunning);
    }

We can then pass in our isRunning bool into our functions:

void Run(bool isRunning)
{
}

void FlipSprite(bool isRunning)
{
}

Privacy & Terms