Friday, 9 December 2011

My 2D Vector class - and why I no longer use it

For Bug Tunnel Defense I created a 2D vector class. The nearest thing built in to Flash is the Vector3D class, but that with four elements is twice as big as I needed, and also uses Number rather than int as I wanted. I wanted something to store 2D grid positions, for game logic, so I created my own class. Then barely used it.

The reasons were twofold. To add a position to another class it was easier to add the position as iX and iY members, as these were much quicker to inspect in Flash's slow and primitive debugger, where expanding a struct/class takes an unnecessarily long time. Sometimes I wanted to stop the breakpoint as every gun or enemy was ticked and being able to see its coordinates without expanding an additional struct made a lot of difference.

The other reason was I planned to use them to pass positions as parameters, as the enemies queried the navigation system for data for example. But this would mean creating a lot of temporary objects every frame, asking a lot more of the garbage collector than should be necessary. So I largely removed them from the code.

The one place I kept them was for static data describing the holes/flux points which I indexed by hand early in development. Doing that now I would just use coordinates on their rotated grid.

Here is the code, pretty minimal but functional. The G... functions convert grid positions to global draw positions.

class Vec2D {
 var iX:int;
 var iY:int;
 function Vec2D(x:int = 0, y:int = 0) {iX = x; iY = y;}  
 function GX():int {return Game.kiTurretSize + Game.kiTowerSize * iX;}
 function GY():int {return Game.kiTurretSize + Game.kiTowerSize * iY;}
 function GVec2D():Vec2D {
  var vRes:Vec2D = new Vec2D(GX(), GY());
  return vRes;
 function Add(right:Vec2D):Vec2D {
  return new Vec2D(iX + right.iX, iY + right.iY);

 function Sub(right:Vec2D):Vec2D {
  return new Vec2D(iX - right.iX, iY - right.iY);
 function Sign():Vec2D {
  var iXRes = iX > 0 ? 1 : (iX < 0 ? -1 : 0);
  var iYRes = iY > 0 ? 1 : (iY < 0 ? -1 : 0);
  return new Vec2D(iXRes, iYRes);


No comments:

Post a Comment