所以我想知道如何根据我按下/按下的键改变我创建的角色图像?
当按下“d”(或任何一个按键)时,我最终会有一个行走动画,但是当刚刚按下“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
解决方法
你必须了解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
这种模式非常频繁,循环本身有一个名称 – 它叫做The Game Loop.
你的代码不起作用,因为你正在使用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,y)
- end
上面的代码具有一定的重复性,可以使用表格进行排除,但我故意将其简单化.
您还会注意到我在love.update函数中包含了dt参数.这一点非常重要,因为您需要它来确保动画在所有计算机中的工作方式相同(调用love.update的速度取决于每台计算机,而dt允许您应对这种情况)
不过,如果你想做动画,你可能想要使用这个Animation Lib或my own.