【问题标题】:How can i animate sprites in lua when i press the right arrow?当我按下右箭头时,如何在 lua 中为精灵设置动画?
【发布时间】:2018-08-12 21:50:31
【问题描述】:

我是 Defold 和编码的新手,我一直在关注 Gamefromscratch 的视频教程来动画精灵,这是一个 https://www.youtube.com/watch?v=ha1Wq2FB7L0&t=5s buto 当我按下右箭头时无法让它移动,它只是处于空闲状态位置。

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

这是代码,正如我所说,当我按下右箭头时它不会像教程那样移动。

【问题讨论】:

    标签: lua 2d sprite defold


    【解决方案1】:

    您在函数 on_input 的第一个 if 语句中拼错了单词“action”。

    这个脚本应该可以工作:

    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
    

    【讨论】:

    • 这是 Lua 的“默认全局”陷阱 :-( 用户不会收到有关拼写错误的标识符的警告。
    • 我们将在 Defold 代码编辑器中添加一个 linter 来警告这些事情。 Atom、Sublime 和其他软件都存在 Lua linters,所以这真的不是什么大问题。
    猜你喜欢
    • 1970-01-01
    • 2010-11-10
    • 2011-02-10
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多