Page 1 of 1

How do you change backgrounds when a key is pressed?

Posted: Fri Dec 30, 2011 12:17 pm
by Randomgajmes
Hi, i am quite new to love2d, but i am playing around with it and starting to get the hang of the basic commands.

So i thought it would be cool if i had a background, then pressed a key, and the background would change. This could also be usefull for making games where you press a key when in the menu and then you suddenly can select a level on an entirely new background.

I got the code working, but when i tested it, the new background just flashes, then the old one comes back. This could have something to do with the fact that i do not remove the old background. If it is as simple as that, please tell me how, if else, tell me anyway.

Thanks in advance! /Randomgajmes

Re: How do you change backgrounds when a key is pressed?

Posted: Fri Dec 30, 2011 12:37 pm
by Robin
Please see the rules. It's hard for us to help you if you don't show us what you're doing. I have a suspicion, but it works better if you upload your code.

Re: How do you change backgrounds when a key is pressed?

Posted: Fri Dec 30, 2011 2:31 pm
by IMP1
You shouldn't really have a love.graphics.draw in the love.keypressed method. Or anywhere outside of love.draw at all.

this is how I'd go about what you seem to be trying to do:

Code: Select all

function love.load()
	love.graphics.setCaption("Seal Off")
  -- Create a table which we will fill with background images.
  backgrounds = {}
  backgrounds[1] = love.graphics.newImage("bg.png")
  backgrounds[2] = love.graphics.newImage("bg2.png")
  -- This is the index of the above table that we're currently drawing.
  backgroundToDraw = 1
  -- This sets the colour in love load, as there's no point setting it to the same thing several times.
  love.graphics.setColor(250,250,250,250)
end

function love.draw()
  -- This draws the background with index 'backgroundToDraw' from the table 'backgrounds'.
	love.graphics.draw(backgrounds[backgroundToDraw])
end

function love.keypressed(key)
	if key == "s" then
    -- This cycles through the indexes of 'backgrounds'.
    -- The hash key '#' is used to determine the lengths of tables.
    -- a % b (where a and b are both numbers) returns the remainder with a is divided by b. 
    -- This is useful when dealing with things like cycling through. 
    -- So assuming we're using the above table which has a size of 2, then the following numbers would
    -- be limited to 1 - 2 ( 1 to the table's size):
    -- 1 % 2 = 1. 1 + 1 = 2
    -- 2 % 2 = 0. 0 + 1 = 1
    -- 3 % 2 = 1. 1 + 1 = 2
    -- 4 % 2 = 0. 0 + 1 = 1
    -- 5 % 2 = 1. 1 + 1 = 2
    -- And so on.
    -- This works for any table size.
		backgroundToDraw = (backgroundToDraw % #backgrounds) + 1
	end
end