| |
|
|
| local Avatar = {} |
| Avatar.__index = Avatar |
|
|
| function Avatar:new(config) |
| local obj = { |
| name = config.name or "Player", |
| x = config.x or 0, |
| y = config.y or 0, |
| speed = config.speed or 100, |
| direction = "down", |
| state = "idle", |
| sprite = config.sprite or nil, |
| frame = 1, |
| frameTime = 0, |
| frameSpeed = config.frameSpeed or 0.1, |
| animations = config.animations or {} |
| } |
|
|
| setmetatable(obj, Avatar) |
| return obj |
| end |
|
|
| |
| function Avatar:setState(state, direction) |
| if state then self.state = state end |
| if direction then self.direction = direction end |
| self.frame = 1 |
| self.frameTime = 0 |
| end |
|
|
| |
| function Avatar:move(dx, dy, dt) |
| if dx == 0 and dy == 0 then |
| self:setState("idle") |
| return |
| end |
|
|
| self.x = self.x + dx * self.speed * dt |
| self.y = self.y + dy * self.speed * dt |
|
|
| |
| if math.abs(dx) > math.abs(dy) then |
| self.direction = dx > 0 and "right" or "left" |
| else |
| self.direction = dy > 0 and "down" or "up" |
| end |
|
|
| self:setState("walk", self.direction) |
| end |
|
|
| |
| function Avatar:update(dt) |
| local animKey = self.state .. "_" .. self.direction |
| local anim = self.animations[animKey] |
|
|
| if anim then |
| self.frameTime = self.frameTime + dt |
| if self.frameTime >= self.frameSpeed then |
| self.frameTime = self.frameTime - self.frameSpeed |
| self.frame = self.frame + 1 |
| if self.frame > #anim then |
| self.frame = 1 |
| end |
| end |
| end |
| end |
|
|
| |
| function Avatar:draw() |
| if not self.sprite then |
| |
| |
| return |
| end |
|
|
| local animKey = self.state .. "_" .. self.direction |
| local anim = self.animations[animKey] |
|
|
| if anim then |
| local quad = anim[self.frame] |
| |
| |
| else |
| |
| |
| end |
| end |
|
|
| return Avatar |
|
|