【问题标题】:can anybody help me to understand this animation 2d code in lua?任何人都可以帮助我理解 lua 中的这个动画 2d 代码吗?
【发布时间】:2018-08-14 21:28:21
【问题描述】:

如你所见,我是一个初学者,我一直在关注关于 lua 的关于二维动画的 defold 视频教程,从那时起我一直在问我一些关于这段代码的问题,为什么局部变量 currentAnimation 等于 0然后在代码上设置为 1,然后是关于 self.currentAnimation,据我所知,currentAnimation 是一种方法,因为它是通过 self 调用的动作,因此对象可以向右移动?

local currentAnimation = 0

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

function final(self)
end

function update(self, dt)

end

function on_message(self, message_id, message, sender)
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
end

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

结束

我应该遵循什么步骤,这样我才能以某种方式更改代码,所以当我从关键字中按下右箭头时,“英雄”会移动,当我停止按下“英雄”时,“英雄”会停止移动,因为使用此代码它不会'在我再次按下同一个按钮之前不会停止移动,顺便说一句,第二段代码是在第一段代码之后自己完成的。

现在我有另一个问题,我想让它在按下指定按钮时跳跃:

if action_id == hash("jump") then
    if action.pressed then
        msg.post("#sprite", "play_animation", {id = hash("heroJump")})
        self.currentAnimation = 0
    else
        msg.post("#sprite", "play_animation", {id = hash("idle")})
    end

end

使用此代码它不会跳转,我尝试了其他代码,但它就像一个循环,使跳转动画越过,我只是希望每次按下指定按钮时它都会跳转。

【问题讨论】:

    标签: animation lua 2d defold


    【解决方案1】:

    currentAnimation 肯定不是一个方法,它是一个恰好名为self 的表的字段。

    local currentAnimation = 0 行达到什么目的,谁都猜不透,之后就再也不用了。

    显然,您提供的代码似乎用于描述对象的行为(实际上是 lua 表)。根据 defold 框架中的manual,您可以使用不同对象之间的消息传递以及为侦听器订阅与您的对象相关的事件来实现行为。 initfinalupdateon_message 以及重要的是,on_input 都是您为特定事件定义的事件处理程序。然后,游戏引擎会在决定这样做时调用它们。

    在处理按下按钮的事件时,您的对象使用该行

    msg.post("#sprite", "play_animation", {id = hash("runRight")})

    向引擎发送消息,指示它应该绘制一些东西并可能执行一些在其他地方定义的行为。

    上面的代码将字符实现为一个简单的finite state automatacurrentAnimation是表示当前状态的变量,1是静止不动,0是跑步。 if 运算符中的代码处理状态之间的转换。按照你目前的做法,需要两次按键来改变运行方向。

    您的on_input 事件处理程序接收到描述事件的action 表,然后它过滤仅处理按下的右键if action_id == hash("right") and action.pressed == true then 的事件(以及您添加的左键检查)。根据documentation,您还可以通过检查字段action.released 来检查按钮是否被释放。如果你想让角色停止,你应该在事件处理程序中添加相应的分支。他们在那里有一堆examples。你可以结合这些来实现你想要的行为。

    【讨论】:

    猜你喜欢
    • 2012-11-13
    • 2015-09-14
    • 2012-10-28
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多