Wednesday, September 2, 2009

Mindless Collision Detection

I'm trying to get all the pieces in the right places and work out the design details for now.  That means that I'll make routines that I know work, but that may not be efficient enough to work in production. 
Of course, it's hard to predict where the bottlenecks will be.  For example, I think that collision detection will have to be tweaked to keep it from bogging down the system.  Statistically speaking, I'm probably going to be wrong.  My experience is that it is hard to think about what is really going to be slow.  Brute force collision detection is basically a lot of math.  Computers are good at math...maybe good enough that I don't have to care about it for now.  Only time will tell.
Anyway, here's my function.  It's about as stupid as can be.  I actually can think of a worse algorithm, but only one.


public List<Pair<Sprite>> FindCollisions() 
{ 
  List<Pair<Sprite>> collisions = new   List<Pair<Sprite>>(); 
  int numSprites = lSprites.Count; 
  for (int i=0; i< numSprites; i++) { 
    for (int j=i+1; j<numSprites; j++) { 
      if (Collides(lSprites[i], lSprites[j])) { 
        collisions.Add(new Pair<Sprite>(lSprites[i], lSprites[j])); 
      } 
    } 
  } 
return collisions; 
} 
I do have a basic test below.  I should add a more complex case, but Connor wants me to tuck him back into bed.

[TestMethod]
public void SimpleCollisionTest()
{
  List<GambitApps.Util.Pair<Sprite>> collisions;

  Sprite s1 = new SimpleShooter.Sprite(5, 5, new System.Windows.Point(10, 10));
  s1.Velocity = new Vector(-3, -3);
  Sprite s2 = new SimpleShooter.Sprite(7, 9, new System.Windows.Point(10, 10));
  s2.Velocity = new Vector(10, 10);

  world.addSprite(s1);
  world.addSprite(s2);

  collisions = world.FindCollisions();
  Assert.IsTrue(collisions.Count == 1);

  world.Update(new TimeSpan(0, 0, 5));

  collisions = world.FindCollisions();
  Assert.IsTrue(collisions.Count == 0);

}

No comments:

Post a Comment