Using a TMetronome

A canvas project provides you with a PaintView method that repeats with a frequency that you set. If you want some changes to occur with a different frequency, you can either base your code on a frame count or, more conveniently, use a TMetronome. In this demonstration the speed of the ascending line is controlled by the metronome. Note that you may need to keep the metronome frequency within an acceptable range for the effect you require. The code follows the program in action. If the program does not work in your current browser, try another such as Chrome. If you see no display at school, the security system might have blocked it. You can try instead this direct link to the program running on its own page.

Metronome Demo
unit Unit1;

interface

uses
  System.Types, System.Metronome, SmartCL.System, SmartCL.Components,
  SmartCL.Application, SmartCL.Game, SmartCL.GameApp, SmartCL.Graphics;

type
  TCanvasProject = class(TW3CustomGameApplication)
    const MOB_WIDTH = 20;
    const MOB_HEIGHT = 25;
    Metronome : TMetronome;
    MobX, LineY: integer;
    GoingUp: Boolean;
    MobY: integer := 100;
  protected
    procedure ApplicationStarting; override;
    procedure ApplicationClosing; override;
    procedure PaintView(Canvas: TW3Canvas); override;
  end;

implementation

procedure TCanvasProject.ApplicationStarting;
begin
  inherited;
  Metronome := TMetronome.Create;
  Metronome.TickFrequency := 40;
  Metronome.OnProgress :=
    procedure (Sender : TMetronome)
    begin
      LineY -= 1;
    end;
  LineY := GameView.Height;
  MobX := (GameView.Width - MOB_WIDTH) div 2;
  GameView.Delay := 5;
  GameView.StartSession(False);
end;

procedure TCanvasProject.ApplicationClosing;
begin
  GameView.EndSession;
  inherited;
end;

procedure TCanvasProject.PaintView(Canvas: TW3Canvas);
begin
  Metronome.Progress(GameView.LastFrameTime);
  // Clear background to teal
  Canvas.FillStyle := 'Green';
  Canvas.FillRectF(0, 0, GameView.Width, GameView.Height);
  Canvas.FillStyle := 'Silver';
  Canvas.BeginPath;
  Canvas.Ellipse(MobX, MobY, MobX + MOB_WIDTH, MobY + MOB_HEIGHT); //leftX, topY, rightX, bottomY
  Canvas.Fill;

  if LineY <= MOB_HEIGHT then
  begin
    LineY := GameView.Height;
    Metronome.TickFrequency := Metronome.TickFrequency + 10;
  end;

  Canvas.StrokeStyle := 'Blue';
  Canvas.BeginPath;
  Canvas.LineF(0, LineY, GameView.Width, LineY);
  Canvas.Stroke;

  if GoingUp = true then
     MobY -= 1
  else
    MobY += 1;
  if MobY <= 0 then
    GoingUp := False
  else if MobY + MOB_HEIGHT >= LineY then
    GoingUp := True;
end;

end.
Programming - a skill for life!

Useful for games, with drawing routines (including transforms and text fonts), images, sprites and WebGL 3D graphics. Now includes Box2D physics and rendering by Pixi.js.