function SpriteDemo
% SpriteDemo animates a circular sprite across the screen.  The image
% follows the mouse, like a huge cursor.
% 
% There are many ways to create animations. The simplest is to show a
% movie, computing all the frames in advance, as in MovieDemo. Sprites may
% be a better approach when you want to show a relatively small object
% moving unpredictably. Here we generate one offscreen window holding the
% sprite image and copy it to the screen for each frame of the animation,
% specifying the screen location by using the destination rect argument of
% Screen 'CopyWindow'.
% 
% See also MovieDemo.
% 
% Thanks to tj <thomasjerde@hotmail.com> for asking how. 
% web http://groups.yahoo.com/group/psychtoolbox/message/1101 ;

% 6/20/02 awi  Wrote it as TargetDemo.  
% 6/20/02 dgp  Cosmetic. Renamed SpriteDemo.

screenNumber=0;
backgroundColor = WhiteIndex(screenNumber);
textColor = BlackIndex(screenNumber); 
spriteColor = BlackIndex(screenNumber);
spriteSize = 200;
spriteRect = [0 0 spriteSize spriteSize];
[w,wRect]=Screen(0,'OpenWindow',backgroundColor);
buttons = 0;
previousX = 0;
previousY = 0;
Screen(w,'TextSize',48);
Screen(w,'TextFont','Arial');
width=Screen(w,'TextWidth','Move the mouse. Click to exit');
Screen(w,'DrawText','Move the mouse. Click to exit',RectWidth(wRect)/2-width/2,RectHeight(wRect)/2,textColor);
wCopy = Screen(w,'OpenOffscreenWindow');
Screen('CopyWindow',w,wCopy);
wSprite = Screen(w,'OpenOffscreenWindow',backgroundColor,spriteRect);
Screen(wSprite,'FillOval',spriteColor);
HideCursor;
while ~any(buttons)
    [mX,mY,buttons] = GetMouse;
    Screen(w,'WaitBlanking');
    % erase the sprite drawn at the previous location
	r=CenterRectOnPoint(spriteRect,previousX, previousY);
    Screen('CopyWindow',wCopy,w,r,r);
    % draw the sprite at the new location.
    Screen('CopyWindow',wSprite,w,spriteRect,CenterRectOnPoint(spriteRect,mX, mY));
    previousX = mX;
    previousY = mY;
end
ShowCursor;
Screen('CloseAll');
