lua2dspritedefold

How can i animate sprites in lua when i press the right arrow?


i'm new to Defold and coding, i have been following a video tutorial from Gamefromscratch to animate sprites which is this one https://www.youtube.com/watch?v=ha1Wq2FB7L0&t=5s buto could not make it move when i press the right arrow, it is just stands in idle position.

local currentAnimation = 0

function init(self)
    msg.post(".", "acquire_input_focus")
end

function final(self)
    -- Add finalization code here
    -- Remove this function if not needed
end

function update(self, dt)
end

function on_message(self, message_id, message, sender)
    -- Add message-handling code here
    -- Remove this function if not needed
    end

function on_input(self, action_id, action)
if aciton_id == hash("right") and action.pressed == true then
    if self.currentAnimation == 1 then
        msg.post("#sprite", "play_animation", {id = hash("runRight")})
        self.currentAnimation = 0
    else 
        msg.post("#sprite", "play_animation", {id = hash("idle")})
        self.currentAnimation = 1
    end
end
end

This is the code, as i said when i press the right arrow it does not move as the tutorial.


Solution

  • You misspelled the word 'action' on the first if statement at function on_input.

    This script should work:

    local currentAnimation = 0
    
    function init(self)
        msg.post(".", "acquire_input_focus")
    end
    
    function final(self)
        -- Add finalization code here
        -- Remove this function if not needed
    end
    
    function update(self, dt)
    
    end
    
    function on_message(self, message_id, message, sender)
        -- Add message-handling code here
        -- Remove this function if not needed
    end
    
    function on_input(self, action_id, action)
      if action_id == hash("right") and action.pressed == true then
        if self.currentAnimation == 1 then
          msg.post("#sprite", "play_animation", {id = hash("runRight")})
          self.currentAnimation = 0
        else 
          msg.post("#sprite", "play_animation", {id = hash("idle")})
          self.currentAnimation = 1
        end
    
        return true
      end
    end