有人能帮我理解这个 Lua 代码中的 2D 动画吗?

如你所见,我是一个初学者,并且一直在关注一个有关 2D 动画的 defold 与 Lua 的视频教程,自那时起,我一直在思考这个代码的一些问题。为什么当前变量 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

我应该怎么做才能更改代码,以便当我按下从关键字“right”开始的右箭头时,“英雄”可以移动,而当我停止按下“英雄”时,它会停止移动,因为使用这段代码它不会停止移动,直到我再次按下相同的按钮,顺便说一下,第二个代码块是我按照第一个代码块自己写的。

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

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

使用这段代码不会跳跃,我尝试了其他代码但会像循环一样使跳跃动画一遍又一遍,我只想让它每次按下指定按钮时跳跃。

点赞
用户4687565
用户4687565

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

local currentAnimation = 0这行代码的目的无从得知,之后也没有被使用。

显然,你提供的代码用于描述对象(实际上是lua表)的行为。在defold框架中,根据手册,您使用消息传递在不同对象之间实现行为,并订阅监听事件与你的对象相关的事件。

initfinalupdateon_message和,更重要的是,on_input是您为特定事件定义的事件处理程序。然后游戏引擎根据需要调用这些程序。

在处理按下按钮事件时,您的对象使用以下代码

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

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

上述代码将字符作为简单的有限状态自动机来实现。currentAnimation是表示当前状态的变量,1表示静止,0表示奔跑。if运算符内部的代码处理状态之间的转换。只有在目前的实现方式下,才需要两次按键以改变奔跑方向。

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

2018-08-15 11:22:42