Advertisement
CluelessDev

State transitioning pattern

Jul 24th, 2023
840
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.89 KB | None | 0 0
  1. local Players = game.Players
  2. local LocalPlayer = Players.LocalPlayer
  3. local Character = LocalPlayer.Character
  4. local Humanoid = Character.Humanoid
  5. local Animator = Humanoid.Animator :: Animator
  6. local Backpack = LocalPlayer.Backpack
  7. local Sword = Backpack:FindFirstChild("Sword") :: Tool
  8.  
  9.  
  10.  
  11. local combatAnimationTracks = {} :: {[string]: AnimationTrack}
  12. local combatConnections = {} :: {[RBXScriptConnection]: true}
  13.  
  14. -- initialize animations and put them in a local list we can refer
  15. for _, anim: Animation in workspace.Anims:GetChildren() do
  16.     local at = Animator:LoadAnimation(anim)
  17.     at.Priority = Enum.AnimationPriority.Action2
  18.     combatAnimationTracks[anim.Name] = at
  19. end
  20.  
  21.  
  22. -- Set State serves as our "change state" function
  23. -- it'll transition from state A to B by cleaning
  24. -- connections and stopping animations specific states
  25. -- might have played/oppened
  26. local function SetState(StateFunction: () -> ()): ()
  27.     for name, animTrack in combatAnimationTracks do
  28.         animTrack:Stop(0)
  29.     end
  30.    
  31.     for connection in combatConnections do
  32.         connection:Disconnect()
  33.     end
  34.    
  35.     StateFunction()
  36. end
  37.  
  38.  
  39. -- state functions
  40. function SwordEquipped()
  41.     combatAnimationTracks.Equip:Play()
  42.    
  43.     local comboCount = 0   
  44.     combatConnections[Sword.Activated:Connect(function()
  45.         comboCount += 1
  46.         local slashAnim = "Slash"..tostring(comboCount)
  47.         print(slashAnim)
  48.         combatAnimationTracks[slashAnim]:Play()
  49.         comboCount %= 2
  50.     end)] = true
  51.    
  52.     combatConnections[Sword.Unequipped:Connect(function()
  53.         combatAnimationTracks.Equip:Play(0.100000001, 1, -1)
  54.         combatAnimationTracks.Equip.Ended:Wait()
  55.         SetState(Idle)
  56.     end)] = true
  57. end
  58.  
  59.  
  60.  
  61. function Idle()
  62.     combatAnimationTracks.Idle:Play()
  63.     combatAnimationTracks.Idle.Looped = true
  64.    
  65.     if Sword then
  66.         combatConnections[Sword.Equipped:Connect(function()
  67.             SetState(SwordEquipped)
  68.         end)] = true
  69.     end
  70. end
  71.  
  72.  
  73. -- Kickstart state management
  74. Idle(LocalPlayer)
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement