0

正如你所看到的,我是一个初学者,我一直在关注关于 defold with lua 关于 2D 动画的视频教程,从那时起我一直在问我一些关于这段代码的问题,为什么局部变量 currentAnimation 等于 0 a 然后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

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

4

1 回答 1

2

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

任何人都猜想这条线的目的是什么local currentAnimation = 0,之后再也没有使用过。

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

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

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

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

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

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

于 2018-08-15T11:22:42.760 回答