Discord
Login
Community
DARK THEME

Mouse hovering

Is there anyway to track mouse hovering? I would like for objects within my game to "light up" when the mouse is over it.

Yep! You can use mouse.x and mouse.y to get the mouse position. Using this, you can have an if statement that toggles a variable like so:

if mouse.x >= -40 and mouse.x <= 70 and mouse.y >= -50 and mouse.y <= -30 then
  hover = 1
else
  hover = 0
end

Now this works fine for if you want to detect a mouse hovering over a rectangle, but what about a circle? Well, that's a bit more tricky. I'll be using a custom-made distance function for this, just to make the code look a bit nicer. Here is the code for it:

dist = function(x, y, x2, y2)
  return sqrt((x-x2)^2 + (y-y2)^2)
end

Now to detect a circle, you need to find the distance from the center of the circle to the mouse position, and find out if it's less than the circle's radius. Basically, if the mouse is close to the middle of the circle this will activate.

if dist(10, 0, mouse.x, mouse.y) then
  hover = 1
else
  hover = 0
end

(10,0 is just the center of the circle in my example, it can really be anything you want)

I'm not sure how to get triangles and other polygons though, sorry. Also, you * might * be able to use a 2d physics engine (you can enable them in settings) and use a collision function or something.

I made an example, if you want to play around with it: https://microstudio.dev/i/JmeJuniper/hoverexample/ (Just clone it :D)

With polygons you either need to be able to create a distance function for different shapes - this is a reference I like to use: https://iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm. You can then check if the distance between the mouse and the shapes is <0 to determine if the mouse is inside the object. You can create any 2d shape with lines and triangles, which should both be included in the above website.

Also, expanding on what JmeJuniper said, you can replicate the rectangle hover with a function like this:

checkmousehover = function(x,y,width,height)
  local rx = abs(x-mouse.x) // get distance in xy dimensions between centre of rectangle and mouse
  local ry = abs(y-mouse.y)
  if rx < width/2 and ry < height/2 then // check if each distance is below the dimensions of the cube
    return true
  else
    return false
  end
end

Then you can use it like this in the draw function for a 'lighting up rectangle':

draw = function()
  screen.clear()
  if checkmousehover(0,0,100,100) then
    // mouse is hovering over rectangle
    screen.fillRect(0,0,100,100,"rgb(0,255,0)")
  else
    // mouse is not hovering over rectangle
    screen.fillRect(0,0,100,100,"rgb(255,0,0)")
  end
end

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community