Page 1 of 1

Mouse functions not working correctly [SOLVED]

Posted: Wed May 01, 2019 4:12 pm
by miniaturedog
Earlier I made a post asking how touch functions in Love2d work and was given the suggestion to try mouse functions instead, since I don't need to manage simultaneous touches. My goal is to make the player move left or right depending on which (horizontal) half of the screen is touched/clicked, but only one side seems to work and I'm not sure which part of my code is causing the problem. Here is a snippet with all of the mouse code from my player.lua file included:

Code: Select all

anim8 = require "libraries/anim8/anim8"

function playerload()
  sprite = love.graphics.newImage("assets/turtle_walking2.png")
 -- player attributes and animations, etc are here
  mouseX = love.mouse.getX()
  mouseLeft = mouseX < love.graphics.getWidth() / 2
  mouseRight = mouseX > love.graphics.getWidth() / 2
end

function playerupdate(dt)
  player.animation:update(dt)

  -- mouse / touch controls
  if love.mouse.isDown(1) and mouseRight then
    player.x = player.x + (player.speed * dt)
    player.animation = player.animations.right
  end
  if love.mouse.isDown(1) and mouseLeft then
    player.x = player.x - (player.speed * dt)
    player.animation = player.animations.left
  end
end

-- idle animations
function love.mousereleased(x, y, button, istouch)
  if mouseRight == true then
    player.animation = player.animations.idleRight
  end
  if mouseLeft == true then
    player.animation = player.animations.idleLeft
  end
end

function playerdraw()
  player.animation:draw(player.sprite, player.x + player.ox, player.y + player.oy, 0, 2, 2, player.ox, player.oy)
end
I also have attached the .love file (which for some reason has appeared with a ".love.zip" extension?). Either way, any help or suggestions are appreciated!

Re: Mouse functions not working correctly

Posted: Wed May 01, 2019 4:45 pm
by keharriso
Add this to player.lua:

Code: Select all

function love.mousepressed(x, y, button, istouch, presses)
  mouseX = love.mouse.getX()
  mouseLeft = mouseX < love.graphics.getWidth() / 2
  mouseRight = mouseX > love.graphics.getWidth() / 2
end

Re: Mouse functions not working correctly

Posted: Wed May 01, 2019 5:16 pm
by miniaturedog
keharriso wrote: Wed May 01, 2019 4:45 pm Add this to player.lua:

Code: Select all

function love.mousepressed(x, y, button, istouch, presses)
  mouseX = love.mouse.getX()
  mouseLeft = mouseX < love.graphics.getWidth() / 2
  mouseRight = mouseX > love.graphics.getWidth() / 2
end
That works perfectly, thank you!

Re: Mouse functions not working correctly [SOLVED]

Posted: Wed May 01, 2019 8:51 pm
by zorg
My understanding is that the x parameter that you get from mousepressed should be the same what love.mouse.getX returns (at the moment you pressed a button somewhere, i mean), so it' practically not needed there; just doing mouseX = x should work.