1
votes

The below is a self-explanatory love2d program sample of mine. The variable 'state' determines the state of the game, i.e, 'play' & 'menu'. The initial state is 'menu' and what is expected to happen here is when first right-clicked, the state changes to 'play', and on further second right-click the variable printMsg is set to true as a result of which a message is printed inside function love.draw().

function love.load()

    state = 'menu'

end

function love.draw()
    
    if printMsg == true then

        love.graphics.print('mousepressed')

    end

end

function love.mousepressed(x, y, button)

    if state == 'menu' and button == 1 then

        state = 'play'

    end

    if state == 'play' and button == 1 then

        printMsg = true

    end

end

I have 2 issues here:

  1. On the first click itself the message is printed because the program tends to think that the first click is also the second click.

  2. Without having to create a variable printMsg to actually print the message, I want to print the message at the instance the button is pressed. What I mean is:

function love.load()

    state = 'menu'

end

function love.draw()

end

function love.mousepressed(x, y, button)

    if state == 'menu' and button == 1 then

        state = 'play'

    end

    if state == 'play' and button == 1 then

        love.graphics.print('mousepressed')

    end

end

but unfortunately, this prints nothing.

Any answers appreciated.

1
For how long should the text be displayed? What should happen if I click for a third time? - Jasmijn
the text should display as long as the state='play'. there is no action for third click. - Nuzri
Thanks but its a completely different topic - Nuzri
Then using elseif with your original code is fine. - Jasmijn

1 Answers

1
votes

You enter the second if statement because you assign 'play' to state. hence the condition of the second if statement is true.

If only one of those things should happen:

if state == 'menu' and button == 1 then
  state = 'play'
elseif state == 'play' and button == 1 then
  love.graphics.print('mousepressed')
end

or

if button == 1 then
  if state == 'menu' then
    state = 'play'
  elseif state == 'play' then
    love.graphics.print('mousepressed')
  end
end

or if you can only have those two options you can omit one of the conditions:

if button == 1 then
  if state == 'menu' then
    state = 'play'
  else
    love.graphics.print('mousepressed')
  end
end

Note that this print will not result in any output. By default Love2d will clear the screen befor invoking love.draw. So anything you print outside love.draw is not taken into account.

Either exclusively draw in love.draw or avoid clearing the frame buffer by implementing your own love.run.