Processing Motion Events

The motion demo supplied with Smart Mobile Studio, Projects\Featured Demos\Forms & Components\Accelerometer\Accelerometer Demo.sproj, is for a form-based project. This little canvas project displays six rectangles, each with width proportional to the value of acceleration (green rectangle) or rotation (red rectangle) for one of the three axes. Compile it on a Windows PC with Smart Mobile Studio then open the resultant HTML file in a mobile device, preferably with a Chrome browser. For the meaning of the data from a motion event see this MDN JavaScript page.

Smart Pascal Code

unit Unit1;

interface

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

type
  TCanvasProject = class(TW3CustomGameApplication)
  private
    FMotion: TW3Motion;
    FAccelX, FAccelY, FAccelZ, FAlpha, FBeta, FGamma: float;
  protected
    procedure ApplicationStarting; override;
    procedure ApplicationClosing; override;
    procedure PaintView(Canvas: TW3Canvas); override;
    procedure HandleMotionChange(Sender: TObject; Info: TW3MotionData);
  end;

implementation

procedure TCanvasProject.HandleMotionChange(Sender: TObject; Info: TW3MotionData);
begin
  FAccelX := Info.AccelInclGravity.X;
  FAccelY := Info.AccelInclGravity.Y;
  FAccelZ :=  Info.AccelInclGravity.Z;
  FAlpha := Info.RotationRate.Alpha;
  FBeta := Info.RotationRate.Beta;
  FGamma := Info.RotationRate.Gamma;
end;

procedure TCanvasProject.ApplicationStarting;
begin
  inherited;
  FMotion := TW3Motion.Create(Document);
  FMotion.OnChange := HandleMotionChange;
  GameView.Delay := 20;
  GameView.StartSession(False);
end;

procedure TCanvasProject.ApplicationClosing;
begin
  GameView.EndSession;
  inherited;
end;
 
procedure TCanvasProject.PaintView(Canvas: TW3Canvas);
begin
  // Clear background
  Canvas.FillStyle := 'rgb(0, 0, 99)';
  Canvas.FillRectF(0, 0, GameView.Width, GameView.Height);
  Canvas.FillStyle := 'black';
  Canvas.FillRectF(GameView.Width / 2 - 1, 0, 2, GameView.Height);
  // Draw rectangles with width proportional to acceleration.
  Canvas.FillStyle := 'rgb(0, 200, 0)';
  Canvas.FillRectF(GameView.Width div 2, 50, FAccelX * 20, 20);
  Canvas.FillRectF(GameView.Width div 2, 100, FAccelY * 20, 20);
  Canvas.FillRectF(GameView.Width div 2, 150, FAccelZ * 20, 20);
  // Draw rectangles with width proportional to rotation rate.
  Canvas.FillStyle := 'rgb(200, 0, 0)';
  Canvas.FillRectF(GameView.Width div 2, 200, FAlpha * 50, 20);
  Canvas.FillRectF(GameView.Width div 2, 250, FBeta * 50, 20);
  Canvas.FillRectF(GameView.Width div 2, 300, FGamma * 50, 20);
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.