State Design Pattern


After completing the combat part of the player mechanics and trying to restrict player control, I faced challenges in implementing the logic. Specifically, I aimed to limit the player to attacking only while grounded and stop movement during certain attack animations, such as the secondary stab attack. As shown in the code snippet below, adding more conditional statements and boolean variables would excessively complicate the logic, potentially making it difficult to manage in the future. So, I think this is the good timing to refactor the code into a more modular structure.

The first step involved separating the input and movement logic. Before, the code directly processed input values and executed movement commands within the same script. By relocating all movement-related logic into a separate script, the "playerController" script now solely handles input detection and delegates movement actions to another class. Additionally, I introduced a boolean variable for each control , such as "canMove," which determines whether the player controller accepts the input change.

Next, I assigned distinct states to the player, allowing for tailored control based on the current state. For this situation, I found the State design pattern is really helpful. During state transitions, I found out it relates with player animations; for example, transitioning from a dodge roll animation to either airborne or grounded animations. Here, integrating the "StateMachineBehaviour" script into the animation state could help me decided the transitions of the player states.

With the current setup, changing control limitations within each state is straightforward. I just need to toggle the corresponding boolean variables upon transitioning to a new state. For example, the attack limitation mentioned above could be done by setting "canMove" to false when entering the stab attack state.

The UML diagrams below show the enhanced setup, shown that it is more modular for adding new animations and action states into the player mechanics. This restructuring  improves the existing code and also enhances scalability and maintainability moving forward.


I was quite satisfied with this change and the smooth transition. I didn't even know I could attached script to animation states before, this finding really helps refactoring the code. I would love to see how this refined framework benefits us as we continue to add more features into the player mechanics.

Chris

Get After The End

Leave a comment

Log in with itch.io to leave a comment.