unit fsprite;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    imgMask: TImage;
    imgSprite: TImage;
    imgCopy: TImage;
    tmrBounce: TTimer;
    cmdSprite: TButton;
    Label1: TLabel;
    procedure cmdSpriteClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure tmrBounceTimer(Sender: TObject);
    procedure FormResize(Sender: TObject);
  private
    { Private declarations }
    dx, dy , X, Y:Integer;
    PicWidth, PicHeight:Integer;
    RightEdge, BottomEdge:Integer;
    Dest, Src: TRect;
    C:TCanvas;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.cmdSpriteClick(Sender: TObject);
begin
  if tmrBounce.Enabled then
  begin
    tmrBounce.Enabled := False;
    cmdSprite.Caption := 'Sprite';
    Refresh;
  end
  else
    begin
      C := Canvas;
      RightEdge  := ClientWidth;
      BottomEdge := ClientHeight;
      Dest.Right := Dest.Left + picWidth;
      Dest.Bottom := Dest.Top + picHeight;
      imgCopy.Canvas.CopyRect (Src, C, Dest);
      cmdSprite.Caption := 'Stop';
      tmrBounce.Enabled := True;
    end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  dx := 15;
  dy := 15;
  picHeight := imgMask.Height;
  picWidth := imgMask.Width;
  imgCopy.Height := picHeight;
  imgCopy.Width := picWidth;

  with Src do
  begin
    Left := 0;
    Top := 0;
    Right := picWidth;
    Bottom := picHeight;
  end;

  Dest.Left := 0;
  Dest.Top := 0;
end;

procedure TForm1.tmrBounceTimer(Sender: TObject);
var
  temp:Integer;
begin
  C.CopyMode := cmSrcCopy;
  C.CopyRect (Dest, imgCopy.Canvas, Src);

  temp := Dest.Left + dx;
  if temp + (picWidth div 2) > RightEdge then
    dx := -Abs(dx)
  else
    if temp < 0 then
      dx := Abs(dx);
    Dest.Left := Dest.Left + dx;
    Dest.Right := Dest.Left + picWidth;

    temp := Dest.Top + dy;
    if temp + (picHeight div 2) > BottomEdge then
      dy := -Abs(dy)
    else
      if temp < 0 then
        dy := Abs(dy);

    Dest.Top := Dest.Top + dy;
    Dest.Bottom := Dest.Top + picHeight;

    imgCopy.Canvas.CopyRect (Src, C, Dest);
    with C do
    begin
      CopyMode := cmSrcAnd;
      CopyRect (Dest, imgMask.Canvas, Src);
      CopyMode := cmSrcInvert;
      CopyRect (Dest, imgSprite.Canvas, Src);
    end;
end;

procedure TForm1.FormResize(Sender: TObject);
begin
  if tmrBounce.Enabled then
  begin //if sprite is running then
    cmdSpriteClick(Application); //Click once to disable
    cmdSpriteClick(Application); //Click again to enable with new coordinates
  end;
end;

end.
