Lua - 检查光标是否在按钮内
Lua - check if cursor is inside of a button
所以基本上我写了这些代码行来检查我的光标是否在按钮内,也就是鼠标悬停。它运行完美,但我真的不喜欢我编写 if 语句 的方式。
--cursor = table containing x and y value of cursor
--self = table containing x and y value of button
--self.W = returns width of button
--self.H = return height of button
function mousover(cursor)
if cursor.x >= self.x --if cursor is inside of button from left side
and cursor.x <= self.x + self.W --if cursor is inside of button from right side
and cursor.y >= self.y --if cursor is inside of button from top side
and cursor.y <= self.y + self.H then --if cursor is inside of button from bottom side
doSomething()
end
有没有更好的方法来编写此 if 语句?也许喜欢做 1 次计算来获取按钮的边界并进行 1 次检查,而不是 4 次来查看光标是否在里面?不知道如何改进,如果你有更好的想法,请分享。
要求:需要使用纯编码Lua,不允许extensions/plugins/etc。
正如我最初在评论中所说:
不,没有更好的方法。
这是传统的边界框检查。边界框有四个边,因此您需要检查四个条件。
想想代码在做什么以及为什么这样做,然后您应该意识到它确实需要做它当前正在做的所有事情。
function mousover(cursor)
if math.floor((cursor.x - self.x)/self.W)^2 +
math.floor((cursor.y - self.y)/self.H)^2 == 0 then
-- DoSomething()
end
end
所以基本上我写了这些代码行来检查我的光标是否在按钮内,也就是鼠标悬停。它运行完美,但我真的不喜欢我编写 if 语句 的方式。
--cursor = table containing x and y value of cursor
--self = table containing x and y value of button
--self.W = returns width of button
--self.H = return height of button
function mousover(cursor)
if cursor.x >= self.x --if cursor is inside of button from left side
and cursor.x <= self.x + self.W --if cursor is inside of button from right side
and cursor.y >= self.y --if cursor is inside of button from top side
and cursor.y <= self.y + self.H then --if cursor is inside of button from bottom side
doSomething()
end
有没有更好的方法来编写此 if 语句?也许喜欢做 1 次计算来获取按钮的边界并进行 1 次检查,而不是 4 次来查看光标是否在里面?不知道如何改进,如果你有更好的想法,请分享。
要求:需要使用纯编码Lua,不允许extensions/plugins/etc。
正如我最初在评论中所说:
不,没有更好的方法。
这是传统的边界框检查。边界框有四个边,因此您需要检查四个条件。
想想代码在做什么以及为什么这样做,然后您应该意识到它确实需要做它当前正在做的所有事情。
function mousover(cursor)
if math.floor((cursor.x - self.x)/self.W)^2 +
math.floor((cursor.y - self.y)/self.H)^2 == 0 then
-- DoSomething()
end
end