how do i check if the mouse pointer is in a square

BlitzMax Forums/BlitzMax Beginners Area/how do i check if the mouse pointer is in a square

Ian Lett(Posted 2011) [#1]
Hi all,

i am trying to check if the mouse is in a particular area(s) of the screen and then doing something , i have a crude check that does multiple IFs and ANDs but its cluncky and slow, what i need is a check along the lines of 'if in range (x,y,h,w) then..

any ideas.

regards
Ian


GfK(Posted 2011) [#2]
If inZone(0,0,32,32)
  'do stuff
EndIf
If inZone(128,128,32,32)
  'do other stuff
EndIf

Function inZone:Byte(x:int,y:int,w:int,h:int)
  If MouseX() >= x
    If MouseX() <= x+w
      If MouseY() >= y
        If MouseY() <= y+h
          Return True
        EndIf
      EndIf
    EndIf
  EndIf
End Function



GfK(Posted 2011) [#3]
Just to add, you could write that entire function on a single line:
  If MouseX() >= x And MouseX() <= x+w and MouseY() >= y and MouseY() <= y+h then Return True

I wouldn't recommend this for two reasons. First, using nested If/EndIf blocks as in the first example, makes the code more readable - though this is a matter of preference. Second, if you have multiple condition checks on a single line, and one of them throws an error, the debugger will just point to the line the error is on rather than which bit of the line is actually causing the problem.


Pengwin(Posted 2011) [#4]
i agree with Gfk, the first method is definitely better during development. However, once I know the function is working, I would probably optimise the code with

Function inZone:Byte(x:int,y:int,w:int,h:int)
    Return MouseX() >= x And MouseX() <= x+w and MouseY() >= y and MouseY() <= y+h
End Function



YellBellzDotCom(Posted 2011) [#5]
Another method that I commonly use is to create a 1x1 pixel that goes wherever the cursor is and I check collisions between that 1x1 pixel and any game objects containing an image.


Czar Flavius(Posted 2011) [#6]
Just to be picky, it can be negligibly faster if you store the mouse x and y in a temp local variable instead of calling it twice. Sorry, I've been away from the forums for a while.


Ian Lett(Posted 2011) [#7]
thanks guys for the help