unit uBox;

interface
uses
  Classes, zglHeader, Math, uMaterials, uObj;
type

{ TBox }

TBox = class(TObj)
  OldX, OldY, A, Z : Single;
  Active, OnHero : Boolean;
  constructor Create(const X, Y : Single); overload;
  procedure Update; override;
  procedure Draw; override;
  procedure DrawBottom; override;
  procedure Activate(B : Boolean); virtual;
end;

var
  Boxs : TList;

implementation
uses
  uHero, uConst, uWorld;

constructor TBox.Create(const X, Y :  Single);
begin
  Init(X, Y, cBoxSize, cBoxSize, $F0F020);
  OldX :=zCircle.cX;
  OldY :=zCircle.cY;
  A := c_maxA + 1;
  Active := false;
  OnHero := false;

  Objs.Add(Self);
  Boxs.Add(Self);
  DynamicObjs.Add(Self);
end;

procedure TBox.Activate(B : Boolean);
var
  tRect : zglTRect;

  function NewPos(X, Y : Single) : boolean;
  begin
    tRect.X := Hero.zRect.X + X;
    tRect.Y := Hero.zRect.Y + Y;
    result := noCollision(tRect);
  end;

begin
  if B then
  begin
    Active := true;
    A := 0;
    OnHero:= false;
    OldX := zCircle.cX - Hero.zCircle.cX;
    OldY := zCircle.cY - Hero.zCircle.cY;
    Hero.Box := Self;
    Hero.zCircle.Radius := DrawRect.Wd2;
  end
  else
  begin
    tRect := zRect;
    if NewPos( - zRect.W - 1, 0)
    or NewPos( + zRect.W + 1, 0)
    or NewPos( 0,  - zRect.H - 1)
    or NewPos( 0,  + zRect.H + 1) then
    begin
      zRect := tRect;
      Active := false;
      A := 0;
      OnHero:= false;
      OldX := zRect.X + zCircle.Radius;
      OldY := zRect.Y + zCircle.Radius;
      Z := zCircle.cY;
      RectUpdate;
      Objs.Add(Self);
      Hero.Box := nil;
      Hero.zCircle.Radius := Hero.DrawRect.Wd2;
    end;
  end;
end;


procedure TBox.Update;
var
  aX, aY : Single;
begin
  if Active then
  begin
    OldX := trunc(10*OldX - OldX) / 10;
    OldY := trunc(10*OldY - OldY) / 10;

    zCircle.cX := Hero.zCircle.cX + OldX;
    zCircle.cY := Hero.zCircle.cY + OldY;
    if A < c_maxA_on then
    begin
      A := A + 0.15;
      zCircle.cY := zCircle.cY - (35*Sin(A));
    end
    else
      OnHero:= true;

    RectUpdate;
    Collision(Self, Hero);
  end
  else
  begin
    if A < c_maxA then
    begin
      A := A + 0.15;
      aY := (20*Sin(A));
      if zCircle.cX <> OldX then
        zCircle.cX := zCircle.cX + trunc(OldX - zCircle.cX) / 10;
      if Z <> OldY then
        Z := Z + trunc(OldY - Z) / 10 ;
      zCircle.cY := Z - aY;
    end;

    RectUpdate;
    Collision(Self);

  end;
  RectUpdate;
  DrawRectUpdate;
end;

procedure TBox.Draw;
begin
  with DrawRect do
    ssprite2d_Draw(mBox, X, Y, 32, 32, 0);
end;

procedure TBox.DrawBottom;
begin
//  with DrawRect do
//    pr2d_Rect(X+Z, Y+35*Sin(A), W, H, $202050, $FF, PR2D_FILL);
end;

end.
