IlanZiin

Basic love2d sprites/movement

Jan 15th, 2023
972
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.97 KB | None | 0 0
  1. _G.love = require('love')
  2.  
  3. function love.load()
  4.     jack = {
  5.         x = 0,
  6.         y = 0,
  7.         sprite = love.graphics.newImage("sprites/spritesheet.png"),
  8.         animation = {
  9.             direction = "right",
  10.             idle = true,
  11.             frame = 1,
  12.             maxframes = 8,
  13.             speed = 20,
  14.             timer = 0.1
  15.         }
  16.     }
  17.  
  18.     SPRITE_WIDTH, SPRITE_HEIGHT = 5352, 569
  19.  
  20.     -- 669 cuz 5352/8 (total sprites)
  21.     QUAD_WIDTH = 669
  22.     QUAD_HEIGHT = SPRITE_HEIGHT
  23.  
  24.     quads = {}
  25.  
  26.     for i=1, 8 do
  27.         quads[i] = love.graphics.newQuad(QUAD_WIDTH * (i - 1), 0, QUAD_WIDTH, QUAD_HEIGHT, SPRITE_WIDTH, SPRITE_HEIGHT)
  28.     end
  29. end
  30.  
  31. function love.update(dt)
  32.     if love.keyboard.isDown("d") then
  33.         jack.animation.idle = false
  34.         jack.animation.direction = "right"
  35.     elseif love.keyboard.isDown("a") then
  36.         jack.animation.idle = false
  37.         jack.animation.direction = "left"
  38.     else
  39.         jack.animation.idle = true
  40.         jack.animation.frame = 1
  41.     end
  42.  
  43.     if not jack.animation.idle then
  44.         jack.animation.timer = jack.animation.timer + dt
  45.  
  46.         if jack.animation.timer > 0.2 then
  47.             jack.animation.timer = 0.1
  48.  
  49.             jack.animation.frame = jack.animation.frame + 1
  50.  
  51.             if jack.animation.direction == "right" then
  52.                 jack.x = jack.x + jack.animation.speed
  53.             elseif jack.animation.direction == "left" then
  54.                 jack.x = jack.x - jack.animation.speed
  55.             end
  56.  
  57.             if jack.animation.frame > jack.animation.maxframes then
  58.                 jack.animation.frame = 1
  59.             end
  60.         end
  61.     end
  62. end
  63.  
  64. function love.draw()
  65.     love.graphics.scale(0.3)
  66.  
  67.     if jack.animation.direction == "right" then
  68.         love.graphics.draw(jack.sprite, quads[jack.animation.frame], jack.x, jack.y)
  69.     else
  70.         love.graphics.draw(jack.sprite, quads[jack.animation.frame], jack.x, jack.y, 0, -1, 1, QUAD_WIDTH, 0)
  71.     end
  72. end
Advertisement
Add Comment
Please, Sign In to add comment