Domanda

Quindi mi chiedevo come cambiare un'immagine del carattere che ho creato a seconda del tasto che ho premuto/pressando?

Il mio ultimo andrà a fare un'animazione ambulante quando viene premuto "D" (o una qualsiasi delle chiavi WASD) ma poi si ferma quando il tasto "D" è appena stato premuto ecc. Tutte le immagini sono già state create.

Ho provato questo ma non ha funzionato:

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
È stato utile?

Soluzione

Devi capire come funziona Löve. (In pratica) fa questo:

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

Questo schema è così frequente che il loop stesso ha un nome - si chiama Il gioco del gioco.

Il tuo codice non funziona perché stai usando love.load() Come se facesse parte del loop di gioco, ma non lo è. Si chiama all'inizio, durante il primo millisecondo del tuo programma e mai più.

Vuoi usare love.load Carica le immagini e love.update per cambiarli:

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

Il codice sopra ha una certa ripetitività che può essere preso in considerazione usando le tabelle, ma l'ho lasciato semplice.

Noterai anche che ho incluso il dt parametro nel love.update funzione. Questo è importante, dal momento che ne avrai bisogno per assicurarti che le animazioni funzionino allo stesso modo in tutti i computer (la velocità con cui love.update è chiamato dipende da ogni computer e dt ti permette di affrontarlo)

Tuttavia, se vuoi fare animazioni, probabilmente vorrai usarlo Animazione lib o il mio.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top