Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- in entity class
- 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 chainFuncs = {}
- for node, count in self.path:nodes() do
- -- go through each node and append a tween
- table.insert(chainFuncs, TweenMovement(0.25, node:getX(), node:getY()))
- end
- -- add function at end to reset path, so we can try a new one
- table.insert(chainFuncs, function(go)
- self.path = nil
- self.target = nil
- self:changeAnimation('idle')
- go()
- end)
- -- chain all movements together and execute
- self:changeAnimation('walking')
- return Chain(unpack(chainFuncs))
- end
- end
- -- in my map class
- function Map:update(dt)
- -- if the entities aren't in a movement turn, chain them to do as much
- if not self.entitiesMoving then
- local chainFuncs = {}
- for k, v in pairs(self.entities) do
- table.insert(chainFuncs, v:attemptPath(math.random(self.mapWidth),
- math.random(self.mapHeight)))
- end
- self.entitiesMoving = true
- Chain(unpack(chainFuncs))()
- end
- for k, v in pairs(self.entities) do
- v:update(dt)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement