ai.lua 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. local this = nil
  2. local animations = { }
  3. function attached(node)
  4. this = node
  5. -- Create an AIAgent for the box
  6. node:setAgent(AIAgent.create())
  7. -- Get state machine
  8. local stateMachine = node:getAgent():getStateMachine()
  9. -- Register AI states
  10. stateMachine:addState("idle")
  11. stateMachine:addState("spin")
  12. stateMachine:addState("slide")
  13. stateMachine:addState("bounce")
  14. stateMachine:addState("scale")
  15. -- Set initial state
  16. stateMachine:setState("spin")
  17. -- Create animations, storing them in a table keyed on state name
  18. animations["slide"] = node:createAnimation("slide", Transform.ANIMATE_TRANSLATE(), 6, { 0, 250, 750, 1250, 1750, 2000 }, { 0,0,0, 2,0,0, 2,0,-4, -2,0,-4, -2,0,0, 0,0,0 }, Curve.LINEAR):getClip()
  19. animations["slide"]:setRepeatCount(AnimationClip.REPEAT_INDEFINITE())
  20. animations["bounce"] = node:createAnimation("bounce", Transform.ANIMATE_TRANSLATE_Y(), 3, { 0, 500, 1000 }, { 0, 0.75, 0 }, Curve.CUBIC_IN_OUT):getClip()
  21. animations["bounce"]:setRepeatCount(AnimationClip.REPEAT_INDEFINITE())
  22. animations["scale"] = node:createAnimation("scale", Transform.ANIMATE_SCALE(), 3, { 0, 750, 1500 }, { 1,1,1, 2,2,2, 1,1,1 }, Curve.QUADRATIC_IN_OUT):getClip()
  23. animations["scale"]:setRepeatCount(AnimationClip.REPEAT_INDEFINITE())
  24. end
  25. function stateEnter(node, state)
  26. local clip = animations[state:getId()]
  27. if clip then
  28. clip:play()
  29. end
  30. end
  31. function stateExit(node, state)
  32. local clip = animations[state:getId()]
  33. if clip then
  34. clip:pause()
  35. end
  36. end
  37. function stateUpdate(node, state, t)
  38. if state:getId() == "spin" then
  39. node:rotateY(t * math.rad(0.05))
  40. end
  41. end
  42. -- Put into the global table so it can be called by game.lua to toggle AI state
  43. function _G.toggleState()
  44. local stateMachine = this:getAgent():getStateMachine()
  45. local state = stateMachine:getActiveState():getId()
  46. if state == "spin" then
  47. stateMachine:setState("slide")
  48. elseif state == "slide" then
  49. stateMachine:setState("bounce")
  50. elseif state == "bounce" then
  51. stateMachine:setState("scale")
  52. elseif state == "scale" then
  53. stateMachine:setState("idle")
  54. elseif state == "idle" then
  55. stateMachine:setState("spin")
  56. end
  57. end