Webcam and motion detection

Screen are the first step to make a game, on the screen we can draw sprites and other type of elements to make our game, this tutorial show how to initialise a webcam how to get information about the movement detected on some zones. For this tutorial example we need a variable called Quit, other for the screen identifier called hScreen, other to allocate the percent of movement detected called MotionPercent, and other to allocate the Device Context for drawing operations called DC:


 Declare Quit.b, hScreen.l, MotionPercent.l, DC.l

Then we can initialise DirectX and open our screen with OpenDXSreen() with size of 640x480 and 16 bits of colors:


 If InitDXSprite() != 0

   hScreen = OpenDXScreen(640, 480, 16, "VM Basic Webcam tutorial") != 0 
  
   If hScreen != 0

Now, we set the motion detection state for our program, and initialise the webcam components:


     SetVideoMode(#VMB_WEBCAM_VIDEOSTREAM) 
     SetMotionDetection(#True, 20) 

     InitWebcam(hScreen) 

After set motion detection options, we open a Webcam requester to connect with a video device driver, and after this we set the area size for motion detection (when you connect with a driver with WebcamRequester() or SelectDriver(), the area coordinate size changes to the video size of driver connected if you not change it after these commands), we draw the image with a size of 640x480, and we will use the same coordinates values to use check motion commands:


     WebcamRequester() 
     SetAreaSize(640, 480) 

Load a bmp sprite as number 0 for normal sprite drawing:


     LoadDXSprite(0, "vmmb.bmp", #VMB_SPRITE_NORMAL) 

Now we add a repeat block of code until user want to quit our program, processing the event with ProcessEvent(). We also draw the webcam image and the sprite on the screen checking the sprite zone for motion detection, we check that screen is actived with IsScreenActive() to not draw the sprite when the screen is minimized:


     Repeat 

       ProcessEvent() 

       If KeyPushed(#VMB_KEY_ESCAPE) = #True 
         Quit = #True 
       EndIf  

       If IsScreenActive(hScreen) = #True 

         MotionPercent = CheckDXSpriteZoneFast(0, 100, 100) 

         DC = GetDXScreenDC() 
         DrawWebcamImage(DC, 0, 0, 640, 480) 
         Text(DC, 10, 10, Add("CheckZone percent: ", Str(MotionPercent)), RGB(0, 0, 255)) 
         ReleaseDXScreenDC(DC) 

         DrawDXSpriteFast(0, 100, 100) 

         FlipDXBuffers(#VMB_SCREEN_CLEAR, RGB(0, 0, 255)) 

       EndIf  

     Until Quit = #True

Now we must to free the sprite loaded and the webcam, close the screen and put the EndIf for DirectX init check and for open screen check and end our program:


   FreeDXSprite(0) 

   FreeWebcam()
 
   CloseDXScreen() 

   EndIf

 EndIf
 
 EndProgram  

Exercise:
Add commands necessary to move the sprite on horizontal direction when user touch the sprite.