Love - Creating a Map

From TRCCompSci - AQA Computer Science
Revision as of 10:32, 27 June 2019 by Admin (talk | contribs) (Loading the tileset)
Jump to: navigation, search

Requirements

You need to have followed the installation process for the Love engine.

You also need to have created a minimal game (ie a new folder, with a 'main.lua' file)

You need to have added this code to 'main.lua':

function love.load()

end

function love.update(dt)

end
 
function love.draw()

end

My code will use this image: Tiles.png

Creating a Map Array

We need a way of storing a map of the tiles. This code below creates a 1D array, a 0 represents no tile and then any number above zero is a specific tile. Add the following before your 'love.load()':

 map = { 
			0, 2, 2, 0, 0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
			0, 4, 4, 0, 0, 0, 2, 2, 0, 0, 
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
			0, 0, 3, 3, 3, 0, 0, 0, 0, 0, 
			0, 0, 0, 0, 0, 0, 4, 4, 0, 0, 
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
		}

Loading the tileset

Now in the 'love.load()' we need to load in your tileset image, and also we can create rectangles for each different tile in the tileset:

function love.load()
	tilesheet = love.graphics.newImage("tiles.png")
	grass = love.graphics.newQuad(0, 0, 32, 32, tilesheet:getDimensions())
	boxtop = love.graphics.newQuad(32, 0, 32, 32, tilesheet:getDimensions())
	flowers = love.graphics.newQuad(0, 32, 32, 32, tilesheet:getDimensions())
	box=love.graphics.newQuad(32, 32, 32, 32, tilesheet:getDimensions())
end

drawing the map

function love.draw()
	count = 0
		for y=0, 9 do 
			for x=0, 9 do
				if map[count] == 1 then
					love.graphics.draw(tilesheet, grass, x*32, y*32, 0, 1, 1)
				elseif map[count] == 2 then
					love.graphics.draw(tilesheet, boxtop, x*32, y*32, 0, 1, 1)
				elseif map[count] == 3 then
					love.graphics.draw(tilesheet, flowers, x*32, y*32, 0, 1, 1)
				elseif map[count] == 4 then
					love.graphics.draw(tilesheet, box, x*32, y*32, 0, 1, 1)
				end
				count=count+1
			end
		end
end