Blitz Basic Tute #4 - Finding the Mouse

When a player clicks on the screen with the mouse, we're going to need to know where she clicked.

MouseX() and MouseY() will tell you.

So try this little program:

graphics 640,480
repeat
  mx=mousex()
  my=mousey()
  text 320,240,"Mouse is at ("+mx+","+my+")",True,True
until keyhit(1)
end

You should have noticed two problems. Firstly, you couldn't see the mouse and, secondly, as you moved the "invisible" mouse the text became unreadable.

To "see" the mouse, we have to draw it! Here's a pointer you can use:
See how far you can get by yourself.

To solve the second problem, we need to clear the screen each time round. Here's what I have so far:

Graphics 640,480
pointer_img=LoadImage("pointer.bmp")
Repeat
  Cls
  mx=MouseX()
  my=MouseY()
  DrawBlock pointer_img,mx,my
  Text 320,240,"Mouse is at ("+mx+","+my+")",True,True
Until KeyHit(1)
FreeImage pointer_img
End

We're getting there ... but ... you would have noticed a dreadful flickering. This is easy to fix but some people find this a little tricky to follow. The idea is that we don't draw directly to the screen, we draw to a "phantom screen" behind the scenes and, when we've finished, "flip" it onto the front screen. This "phantom screen" is called the BackBuffer. Here's the final program ... study it very, very carefully. And, when you're running it, study the values so you learn how Blitz Basic "sees" the screen. Note that x and y are not what we are used to!

Graphics 640,480
SetBuffer BackBuffer()
pointer_img=LoadImage("pointer.bmp")
Repeat
  Cls
  mx=MouseX()
  my=MouseY()
  DrawBlock pointer_img,mx,my
  Text 320,240,"Mouse is at ("+mx+","+my+")",True,True
  Flip
Until KeyHit(1)
FreeImage pointer_img
End

Valid HTML 4.0 Strict Valid CSS