Wednesday, October 6, 2010

More on maps and sprites

This is a full example on how you can check collisions against a map (look at CheckTiles() and see how easy is to check for collisions):





This silly demo is done with the following code

unit Game;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs,
  BB.Screen.Maps, BB.Screen.Interfaces, BB.Screen.Sprites, BB.Screen.Types;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    FShip: TAnimationSprite;

    procedure CheckTiles(aLayer: TLayer; aCell: PCell; aTile: ISprite);
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses
  BB.Screen, BB.Screen.D3D, BB.Screen.Engines, BB.Input.Keys, BB.Timer, BB.Colors;

procedure TForm1.CheckTiles(aLayer: TLayer; aCell: PCell; aTile: ISprite);
var
  x, y: integer;
  spurk: TAnimationSprite;

begin
  if FShip.Collision(aTile, x, y) then
  begin
    spurk := TAnimationSprite.Create;
    spurk.CoordinateOrigin := coCenter;
    spurk.Engine := FShip.Engine;
    spurk.AnimationName := 'spurk';
    spurk.X := x;
    spurk.Y := y;
    spurk.AttachedSprite := FShip;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
var
  gd: TGraphicDriver;
  map: TMap;
  e: TSpriteEngine;

begin
  gd := TD3DDriver.Create;
  gd.WindowHandle := WindowHandle;
  gd.Width := Width;
  gd.Height := Height;
  gd.BPP := 32;
  gd.ScreenFlags := [sfClear, sfWait];
  gd.Initialize;

  map := TMap.Create;
  map.FileName := 'space';
  map.LoadFile;
  map[0].OnRenderTile := CheckTiles;
  map[0].GoLeft;
  map[0].SpeedX := 1;

  e := TSpriteEngine.Create;
  e.ScanMethod := smBox;
  e.FileNames.Add('ship.bmp');
  e.LoadFile;

  FShip := TAnimationSprite.Create;
  FShip.Engine := e;
  FShip.CollisionShape := csPrecise;
  FShip.CollisionAccuracy := caLow;
  FShip.AnimationName := 'ship';
  FShip.Layer := map[0];
  FShip.GoCenterY;

  repeat
    if Inkey(VK_P) then
      WaitFor(VK_P);

    if Inkey(VK_LEFT) then
      FShip.MoveLeft(2);
    if Inkey(VK_RIGHT) then
      FShip.MoveRight(2);

    if Inkey(VK_UP) then
      FShip.MoveUp(2);
    if Inkey(VK_DOWN) then
      FShip.MoveDown(2);

    gd.BeginRender;

    map.Render;
    e.Render;

    gd.EndRender;
    Application.ProcessMessages;

  until Inkey(VK_ESCAPE);

  Close;
end;

end.

No comments:

Post a Comment