Getting mouse position and playing sound with Lua in Love2D

断了今生、忘了曾经 提交于 2020-01-05 03:47:06

问题


I'm writing a little game for visual deficient people, but I'm having a hard time getting the mouse position. Let me explain :

I need to know where in the table the mouse cursor is, without having a click, and then I want to play a sound. That sound would be different for every position. Any thoughts? Thanks, in advance!

e.g., when the mouse is on the 1st box would be played the audio "a1", when it's on the 2nd box, "a2", and so on.

I tried with:

mouse_x, mouse_y = get_Position()

if mouse_x and mouse_y == map[x][y] then
if map[x][y] == 0.1 then
Audio:play()

But it makes a loop and the sound keeps playing forever!


回答1:


I think part of the problem relates to how precise love2d is able to be with it's mouse.

You'll most likely have to change some of the logic in your code around to be more like

(There's four different scenario's because of the ordering in house 1 and 2 would be assigned)

if map.x1 < mouse_x < map.x2 and map.y1 < mouse_y < map.y2 or
map.x1 > mouse_x > map.x2 and map.y1 > mouse_y > map.y2 or
map.x1 < mouse_x < map.x2 and map.y1 > mouse_y > map.y2 or
map.x1 > mouse_x > map.x2 and map.y1 < mouse_y < map.y2 then
     TEsound.play(soundList, "a1", 1, 0.1)
end

Here's an image that explains detecting if the mouse for an eraser is overlapping with a line.

With only 2 x and y coordinates, that example above will probably all be too precise, and you may have to expand the range that the mouse reaches by adding and subtracting small numbers on each side of the inequality.

if (map.x1 - 2 < mouse_x and map.x2 + 2 > mouse_x and map.y1 - 2 < mouse_y and map.y2 + 2 > mouse_y)
            or (map.x1 + 2 > mouse_x and map.x2 - 2 < mouse_x and map.y1 + 2 > mouse_y and map.y2 - 2 < mouse_y)
            or (map.x1 - 2 < mouse_x and map.x2 + 2 > mouse_x and map.y1 + 2 > mouse_y and map.y2 - 2 < mouse_y)
            or (map.x1 + 2 > mouse_x and map.x2 - 2 < mouse_x and map.y1 - 2 < mouse_y and map.y2 + 2 > mouse_y)

Or another option would be to use 4 x coordinate's and 4 y coordinates, assuming your selecting a 2D area



来源:https://stackoverflow.com/questions/53633048/getting-mouse-position-and-playing-sound-with-lua-in-love2d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!