Advertisement
Guest User

Untitled

a guest
Mar 29th, 2017
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. -- in entity class
  2. function Entity:attemptPath(pathX, pathY)
  3. -- acquire path
  4. repeat
  5. self.path = self.map.finder:getPath(self.tileX, self.tileY, pathX, pathY)
  6. pathX = math.random(self.map.mapWidth)
  7. pathY = math.random(self.map.mapHeight)
  8. until self.path
  9.  
  10. -- chain movements in path
  11. if self.path then
  12. self.target = {
  13. x = (pathX - 1) * self.map.tileWidth,
  14. y = (pathY - 1) * self.map.tileHeight
  15. }
  16.  
  17. -- tween movement for X and Y over seconds
  18. local function TweenMovement(seconds, newX, newY)
  19. return function(go)
  20. -- change direction based on X movement
  21. if newX < self.tileX then
  22. self.direction = 'left'
  23. elseif newX > self.tileX then
  24. self.direction = 'right'
  25. end
  26.  
  27. Timer.tween(seconds, {
  28. [self] = {
  29. -- tween pixel movement
  30. x = (newX - 1) * self.map.tileWidth,
  31. y = (newY - 1) * self.map.tileHeight
  32. }
  33. })
  34. :finish(function()
  35. -- keep our grid location updated
  36. self.tileX = newX
  37. self.tileY = newY
  38. go()
  39. end)
  40. end
  41. end
  42.  
  43. -- list of movement tweens we will chain
  44. local chainFuncs = {}
  45. for node, count in self.path:nodes() do
  46.  
  47. -- go through each node and append a tween
  48. table.insert(chainFuncs, TweenMovement(0.25, node:getX(), node:getY()))
  49. end
  50.  
  51. -- add function at end to reset path, so we can try a new one
  52. table.insert(chainFuncs, function(go)
  53. self.path = nil
  54. self.target = nil
  55. self:changeAnimation('idle')
  56. go()
  57. end)
  58.  
  59. -- chain all movements together and execute
  60. self:changeAnimation('walking')
  61. return Chain(unpack(chainFuncs))
  62. end
  63. end
  64.  
  65. -- in my map class
  66. function Map:update(dt)
  67. -- if the entities aren't in a movement turn, chain them to do as much
  68. if not self.entitiesMoving then
  69. local chainFuncs = {}
  70. for k, v in pairs(self.entities) do
  71. table.insert(chainFuncs, v:attemptPath(math.random(self.mapWidth),
  72. math.random(self.mapHeight)))
  73. end
  74. self.entitiesMoving = true
  75. Chain(unpack(chainFuncs))()
  76. end
  77.  
  78. for k, v in pairs(self.entities) do
  79. v:update(dt)
  80. end
  81. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement