Wednesday, October 13, 2010

Scanning a surface to get a shape

In BB.Screen.Extras there is a very useful class called TSurface2Poly which is used in the collision class, its only purpose is to scan a surface and create a set of vertices (aka polygon), the skeleton looks like this:


TSurface2Poly = class
public
  constructor Create(aSurface: ISurface);
  destructor Destroy; override;
  function Execute: IShape;
  function ToString: string; override;

  property Tolerancy: integer read FTolerancy write FTolerancy;
  property Z: TFloat read FZ write FZ;
end;
You pass an ISurface as parameter and you get a IShape in response, quite easy. 
The Z means that the vertices will set the Z value according to this property, then the other property is Tolerancy, this is a funny one, let me explain it.
The main process is something like silhouette detection (not sophisticated in any aspect!), from a given surface we scan all pixels taking into account gaps and 
direction changes.
The secondary process takes the resultant shape and tries to optimize it (take 
into account that a shape for an average surface might have thousands vertices, 
for example, the collision test between two shapes with 10.000 produces a terrible
amount of comparisons, which ends up in slowness), this is where the Tolerancy 
values plays his role, I only add vertices that had an angle greater to the 
property with the previous vertex, I know is a bit silly process, but for now it works and the function is adequately isolated, so rewrite it should be easy.

The surface

After the scan


Depending on the tolerancy it might end up into a rhombus, that is up to you...
The main adventage of this way of handling collisions is that you don't have to care if the sprite is rotated or zoomed, the collisions still works (in counterpart with pixel collisions)

No comments:

Post a Comment