Getting Started with Lua + LÖVE: Part 4

Series:

Using Images

Like the existing use of the physics body (created in love.load) and the drawing (in love.draw) added in the last part, images are also broken up into the same parts: the first, initial load and the later drawing call as part of a larger loop.

Similar to the move away from a player.x and player.y through using the physics body as the base measurement for movement and drawing, the introduction of an image allows for removing the player.width and player.height key-value pairs. Instead of hard-coding those measurements, the width and height of the physics body will be dictated by the width and height of the image itself.

The updated player section would now look like the following:

GitHub Gist:

Pre-formatted:

  player = {}
  player.image = love.graphics.newImage( "player.png" )
  
  player.body = love.physics.newBody( world, 100, 100, "dynamic" )
  
  player.shape = love.physics.newRectangleShape(
    player.body:getX(),
    player.body:getY(),
    player.image:getWidth(),
    player.image:getHeight()
  ) 
  player.fixture = love.physics.newFixture(player.body, player.shape, 1);

Now, the physics shape is based on the image itself. By changing it, all other measurements adjust accordingly.

Of course, like with the move into using a physics body, the drawing calls needs to also change. However, instead of using love.graphics.rectangle, this time the function used will be love.graphics.draw.

GitHub Gist:

Pre-formatted:

function love.draw()
  
  love.graphics.draw(player.image, player.body:getX(), player.body:getY() )
  
end

Updated “main.lua” Example:

GitHub Gist:

Pre-formatted:

function love.load()
  
  love.physics.setMeter(64) 
  
  world = love.physics.newWorld( 0, 0, true )
  
  player = {}
  
  player.image = love.graphics.newImage( "player.png" )
  
  player.body = love.physics.newBody( world, 100, 100, "dynamic" )
  
  player.shape = love.physics.newRectangleShape(
    player.body:getX(),
    player.body:getY(),
    player.image:getWidth(),
    player.image:getHeight()
  ) 
  
  player.fixture = love.physics.newFixture(player.body, player.shape, 1);
  
end

function love.update(dt)
  
  world:update(dt)
  
  if love.keyboard.isDown("up") then
    player.body:applyForce(0, -40)
  end
  
  if love.keyboard.isDown("down") then
    player.body:applyForce(0, 40)
  end
  
  if love.keyboard.isDown("left") then
    player.body:applyForce(-40, 0)
  end
  
  if love.keyboard.isDown("right") then
    player.body:applyForce(40, 0)
  end
  
end

function love.draw()
  
  love.graphics.draw(player.image, player.body:getX(), player.body:getY() )
  
end

Image (player.png):

player