How to create a walking animation in LOVE 2D

柔情痞子 提交于 2019-12-03 06:43:30

You must understand how LÖVE works. It (very basically) does this:

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

This schema is so frequent that the loop itself has a name - it's called The Game Loop.

Your code does't work because you are using love.load() as if it was part of the game loop, but it isn't. It's called at the beginning, during the first millisecond or so of your program, and never again.

You want to use love.load do load the images, and love.update to change them:

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

The code above has certain repetitiveness that can be factored out using tables, but I've left it simple on purpose.

You will also notice that I have included the dt parameter in the love.update function. This is important, since you will need it to make sure that animations work the same in all computers (the speed at which love.update is called depends on each computer, and dt allows you to cope with that)

Nevertheless, if you want to do animations, you will probably want to use this Animation Lib or my own.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!