All Questions


Michael Flaherty

Why is get_input_direction a static function?

You say in the video that we are making this function static "so we don't access any state". Can anyone please explain what that means and why we wouldn't want to do it?
  • Nathan Lovato replied

    From a static function, you cannot access the object's properties. You must pass every bit of data to the function, and the function returns a result.

    Changing state, that is to say, modifying variables directly, is one of the main sources of bugs in computer programming. You've certainly experienced bugs where you had just forgotten to set a boolean back to true, or you had changed the character's speed in some other script and forgot to reset it. Static functions prevent that.

    In this case, I wouldn't recommend to use a static function necessarily, as it can get a bit inconvenient to write, but I would still encourage everyone to calculate and return a new value without modifying any variable, and to group assignments to variables in _physics_process. When you follow this kind of guideline, you reduce the space in which bugs can appear. It makes it relatively easy to find and to solve bugs.

    You would typically want to use static functions in utility libraries, for example if you created a class just for drawing helpers, calculating geometric shapes, etc.

  • F
    Michael Flaherty replied

    Thank you, that makes sense :)