Friday, December 13, 2013

Observer and Observable

In BB framework what to do when there is a relationship between entities and one of them dies?

TDummySprite inherits from TComponentEx which implements the Observable/Observer pattern.

So for example bubbles are solid temporally so any enemy or hero itself can be on top of them, but since a  bubble can suddenly explode, the sprites needs to be informed in order to remove the reference, this is how I did it:

procedure TGameSprite.SetCarryTile(aTile: ISprite);
begin
  if FCarryTile = aTile then
    Exit;

  TriggerSpring(aTile);
  TriggerBalls(aTile);
  StopJumping;

  if aTile <> nil then
  begin
    //So for instance if a sprite is on top of a bubble and this bubble explodes (it dies), sprite is informed and can react
    (aTile as IObservable).AddObserver(self);

    Y := GetContactPlatformY(Gravity, aTile);
    if Gravity = gDown then
      Y := Y - Height;

    if State = ssFalling then
      State := ssWalking;
  end else
  begin
    HorizontalSpeed := 0;
    VerticalSpeed := 0;

    RestoreSpeeds;
  end;

  FCarryTile := aTile;
end;

And then override the method Update()
procedure TGameSprite.Update(aMessage: TMessage);
begin
  inherited;

  if aMessage.Sender = CarryTile as TObject then
    CarryTile := nil;
end;

And there you can update your pointer to nil.

No comments:

Post a Comment