如何在LOVE 2D中创建一个行走动画

8

我想知道如何根据我按下/正在按下的键来改变所创建的角色的图像?

当按下“d”(或任何wasd键)时,我的最终目标是出现行走动画,但当刚刚按下“d”键时,他会站在原地。所有图像都已经创建好了。

我尝试过这个,但它没有奏效:

function love.load()

    if love.keyboard.isDown("a") then
        hero = love.graphics.newImage("/hero/11.png")
    elseif love.keyboard.isDown("d") then
        hero = love.graphics.newImage("/hero/5.png")
    elseif love.keyboard.isDown("s") then
        hero = love.graphics.newImage("/hero/fstand.png")
    elseif love.keyboard.isDown("w") then
        hero = love.graphics.newImage("/hero/1.png")
    end

function love.draw()

    love.graphics.draw(background)
    love.graphics.draw(hero, x, y)

end
1个回答

23

你必须了解LÖVE的工作原理。它(非常基本地)做了这些事情:

love.load()       -- invoke love.load just once, at the beginning
while true do     -- loop that repeats the following "forever" (until game ends)
  love.update(dt) --   call love.update() 
  love.draw()     --   call love.draw()
end

这种模式如此频繁,以至于循环本身都有一个名字 - 它被称为游戏循环

你的代码无法工作,因为你正在使用love.load(),仿佛它是游戏循环的一部分,但实际上不是。它在程序开始时,在第一毫秒左右被调用,之后就再也没有被调用过了。

你想要使用love.load来加载图像,而使用love.update来改变它们:

function love.load()
  heroLeft  = love.graphics.newImage("/hero/11.png")
  heroRight = love.graphics.newImage("/hero/5.png")
  heroDown  = love.graphics.newImage("/hero/fstand.png")
  heroUp    = love.graphics.newImage("/hero/1.png")

  hero = heroLeft -- the player starts looking to the left
end

function love.update(dt)
  if     love.keyboard.isDown("a") then
    hero = heroLeft
  elseif love.keyboard.isDown("d") then
    hero = heroRight
  elseif love.keyboard.isDown("s") then
    hero = heroDown
  elseif love.keyboard.isDown("w") then
    hero = heroUp
  end
end

function love.draw()
  love.graphics.draw(background)
  love.graphics.draw(hero, x, y)
end

上面的代码存在一定的重复性,可以使用表格进行因式分解,但我故意保持了它的简单。

您还会注意到我在love.update函数中包含了dt参数。这很重要,因为您需要它来确保动画在所有计算机上都能以相同的方式工作(love.update被调用的速度取决于每台计算机,而dt使您可以应对这种情况)。

尽管如此,如果您想做动画,您可能会想要使用这个动画库我的动画库


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接