Below shows my code to animate the player sprite when they move.
Code
function init(self)
msg.post(".","acquire_input_focus")
self.runSpeed = 100
self.curAnim = "Idle"
msg.post("#sprite", "play_animation", { id=hash("Idle") })
self.speed = vmath.vector3()
end
function update(self, dt)
local pos = go.get_position()
if self.speed.x ~= 0 then
pos = pos + self.speed * dt
go.set_position(pos)
if self.curAnim ~= "Run" then
msg.post("#sprite", "play_animation", { id=hash("Run") })
self.curAnim = "Run"
end
else
pos = pos + self.speed * dt
go.set_position(pos)
if self.curAnim ~= "Idle" then
msg.post("#sprite", "play_animation", { id=hash("Idle") })
self.curAnim = "Idle"
end
end
if self.speed.y > 0 then
pos = pos + self.speed * dt
go.set_position(pos)
if self.curAnim ~= "Up" then
msg.post("#sprite", "play_animation", { id=hash("Up") })
self.curAnim = "Up"
end
elseif self.speed.y < 0 then
pos = pos + self.speed * dt
go.set_position(pos)
if self.curAnim ~= "Centre" then
msg.post("#sprite", "play_animation", { id=hash("Centre") })
self.curAnim = "Centre"
end
else
pos = pos + self.speed * dt
go.set_position(pos)
if self.curAnim ~= "Idle" then
msg.post("#sprite", "play_animation", { id=hash("Idle") })
self.curAnim = "Idle"
end
end
end
function on_input(self, action_id, action)
if action_id == hash("right") then
self.speed.x = self.runSpeed
sprite.set_hflip("#sprite", false)
end
if action_id == hash("left") then
self.speed.x = self.runSpeed * -1
sprite.set_hflip("#sprite", true)
end
if action_id == hash("up") then
self.speed.y = self.runSpeed
sprite.set_hflip("#sprite", false)
end
if action_id == hash("down") then
self.speed.y = self.runSpeed * -1
sprite.set_hflip("#sprite", false)
end
if (action_id == hash("up") and action.released) or (action_id == hash("down") and action.released) then
self.speed.y = 0
sprite.set_hflip("#sprite", false)
end
if (action_id == hash("right") and action.released) or (action_id == hash("left") and action.released) then
self.speed.x = 0
sprite.set_hflip("#sprite", false)
end
end
The player moves fine, and stops when the keys are pressed. However, nothing I do can make the animations play. For example, when the player moves up, the player faces away from the camera. It loads the initial frame, but doesn’t actually play the animation.
Here are my animations:
Any ideas on how to fix this?