Lua - 检查光标是否在按钮

时间:2015-08-25 16:01:52

标签: button lua position

所以基本上我写了这些代码行来检查我的光标是否在一个名为mousover的按钮内。它完美无缺,但我真的不喜欢我写 if-statement 的方式。

--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-statement ?也许喜欢做1计算来获得按钮的边界并做1检查,而不是4来看看光标是否在里面?不知道如何改进这一点,如果你有更好的主意,请分享。

要求:需要以普通Lua编码,不允许使用扩展/插件/等。

2 个答案:

答案 0 :(得分:3)

正如我最初在评论中所述:

没有没有更好的方法。

这是传统的边界框检查。边界框有四个边,因此您需要检查四个条件。

考虑代码正在做什么以及它为什么这样做,然后你应该意识到它确实需要做它目前正在做的所有事情。

答案 1 :(得分:-1)

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