Skip to content

Instantly share code, notes, and snippets.

@coltonoscopy
Last active March 29, 2017 19:17
Show Gist options
  • Save coltonoscopy/7475bcd4ad3892641d6c348816cb09fd to your computer and use it in GitHub Desktop.
Save coltonoscopy/7475bcd4ad3892641d6c348816cb09fd to your computer and use it in GitHub Desktop.
function Entity:attemptPath(pathX, pathY)
-- acquire path
repeat
self.path = self.map.finder:getPath(self.tileX, self.tileY, pathX, pathY)
pathX = math.random(self.map.mapWidth)
pathY = math.random(self.map.mapHeight)
until self.path
-- chain movements in path
if self.path then
self.target = {
x = (pathX - 1) * self.map.tileWidth,
y = (pathY - 1) * self.map.tileHeight
}
-- tween movement for X and Y over seconds
local function TweenMovement(seconds, newX, newY)
return function(go)
-- change direction based on X movement
if newX < self.tileX then
self.direction = 'left'
elseif newX > self.tileX then
self.direction = 'right'
end
Timer.tween(seconds, {
[self] = {
-- tween pixel movement
x = (newX - 1) * self.map.tileWidth,
y = (newY - 1) * self.map.tileHeight
}
})
:finish(function()
-- keep our grid location updated
self.tileX = newX
self.tileY = newY
go()
end)
end
end
-- list of movement tweens we will chain
local moveChain = Chain()
for node, count in self.path:nodes() do
-- go through each node and append a tween
moveChain(TweenMovement(0.25, node:getX(), node:getY()))
end
-- add function at end to reset path, so we can try a new one
moveChain(function(go)
self.path = nil
self.target = nil
self:changeAnimation('idle')
go()
end)
self:changeAnimation('walking')
-- export movement chain so it can be chained with others later
return function(go)
moveChain()
go()
end
end
end
function Map:update(dt)
-- if the entities aren't in a movement turn, chain them to do as much
if not self.entitiesMoving then
self.entitiesMoving = true
local moveChain = Chain()
for k, v in pairs(self.entities) do
moveChain(v:attemptPath(math.random(self.mapWidth),
math.random(self.mapHeight)))
end
-- set entities not moving flag as last link in the chain
moveChain(function(go) self.entitiesMoving = false end)
moveChain()
end
for k, v in pairs(self.entities) do
v:update(dt)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment