Sordie.co.uk

libsassy/libSassy.Physics2D.pas

Raw

{(
 )) libSassy.Physics2D
((    2D Rigid body physics library
 ))
((  Copyright  Sordie Aranka Solomon-Smith 2016
 ))
((  This work is made available under the terms of the Creative Commons
 )) Attribution-NonCommercial-ShareAlike 3.0 Unported license
((  http://creativecommons.org/licenses/by-nc-sa/3.0/
 )}

unit libSassy.Physics2D;

interface

uses
  libSassy.Maths,
  libSassy.Geometry,
  libSassy.Arrays;

type
{$REGION 'TBody'}
  TBody = class
  private
    fShape: TVectors2;
  public
    Position: TVector4;
    Velocity: TVector4;
    Friction: TVector4;

    Mass:    Single;
    Moment:  Single;

    constructor Create;
    destructor  Destroy; override;

    procedure Update(Delta: Single); virtual;

    procedure ApplyImpulse(Impulse, Position: TVector2);
    procedure ApplyForce(Force, Angle: Single; Position: TVector2);

    property Shape: TVectors2 read fShape;
  end;
{$ENDREGION}

{XY to LR Mix note: L=Y+X; R=Y-X;}

implementation

{$REGION 'TBody'}
constructor TBody.Create;
begin
  inherited;

  fShape := TVectors2.Create;

  Mass   := 10;
  Moment := 10;

  Friction.X := 1;
  Friction.Y := 1;
  Friction.A := 1;
end;

destructor TBody.Destroy;
begin
  fShape.Free;

  inherited;
end;

procedure TBody.Update;
begin
  Velocity := Velocity * Friction;
  Position := Position + (Velocity * Delta);
end;

procedure TBody.ApplyImpulse;
begin
  Velocity.XY := Velocity.XY + (Impulse / Mass);
  Velocity.A  := Velocity.A  + (Position.PerpDotProduct(Impulse) / Moment);
end;

procedure TBody.ApplyForce;
begin
  ApplyImpulse(TVector2.CreateSinCos(Self.Position.A + Angle) * Force, Position.Rotate(-Self.Position.A));
end;
{$ENDREGION}

end.