Inspiaaa / UnityHFSM

A simple yet powerful class-based hierarchical finite state machine for Unity
MIT License
1.05k stars 121 forks source link

Best way to handle FixedUpdate code (physics)? #18

Closed erdostamasa closed 8 months ago

erdostamasa commented 1 year ago

I'm creating a state machine for an enemy which uses physics to move. I'm calling Rigidbody.AddForce() in FixedUpdate to move the enemy. How can I do this in UnityHFSM? I can only use OnLogic. I could put it in the FixedUpdate() method but that would run everything there, even those commands that I only need is regular Update().

Maybe I'm just missing something obvious here. If not, is it possible to have both an OnLogic and an OnFixedLogic (or something like that) so I can have separate Update and FixedUpdate code for states?

MadScientist11 commented 1 year ago

You can do it, see the Actions section in the Wiki - https://github.com/Inspiaaa/UnityHFSM/wiki/Feature-Overview

AyoubOuddah commented 1 year ago

Indeed, as @quizandpuzzle mentioned, actions can be used for FixedUpdate. The problem is if you are implementing an HFSM and you want to factor out some FixedUpdate code, HybridStateMachine class does not support adding actions. Is there a solution for this problem?

erdostamasa commented 1 year ago

@quizandpuzzle I somehow missed that wiki section, thanks! @AyoubOuddah It just happens that I would like a hierarchical state machine. I'm also interested in any possible solution here.

Inspiaaa commented 1 year ago

Hi @erdostamasa,

Using the action system with a hierarchical state machine currently works perfectly fine, as all events (for the actions) are propagated down the hierarchy.

However, as @AyoubOuddah has pointed out, at this point in time you cannot create separate actions in the HybridStateMachine class that are run in addition to those defined in the child states. This means that you cannot factor out common code. The point you bring up about adding actions to the HybridStateMachine class is nevertheless a good idea and I intend to add this to a future release :+1:.

OwenMagelssen commented 1 year ago

The action system approach doesn't seem to work well when creating states and sub state machines as concrete class implementations. While you can inherit from ActionState for an individual state to utilize the action system, there doesn't seem to be a way to accomplish the equivalent for a sub state machine.

Inspiaaa commented 8 months ago

Thanks for the feedback!

I have implemented the aforementioned feature request regarding the HybridStateMachine class in the recent 2.0 release.

The latest release allows you to define custom actions in HybridStateMachines that are run in addition to the actions of the sub-states. As to the order of execution, it will run actions defined in the HybridStateMachine first, before propagating the action further down the hierarchy to the sub-states.

For a usage example, please see the changelog.