I've been working on adding a color based collision component which takes a list of colors and checks to see if an object is colliding with any of them. However, the operation seems to be extremely expensive, even though I am only colliding 2 objects. I think something is wrong with my TestCollision method but, I can't find the error.
public List<Color> Colors = new List<Color>();
private Texture2D _texture;
public Texture2D Texture
{
get { return _texture; }
set
{
_texture = value;
ColorData = _texture.GetData();
}
}
public Color[,] ColorData { get; private set; }
public PerColorCollision(Entity e, string name) : base(e, name)
{
ColorsColliedWith = new List<Color>();
}
public PerColorCollision(Entity e, string name, Texture2D texture) : base(e, name)
{
Texture = texture;
ColorsColliedWith = new List<Color>();
}
public List<Color> ColorsColliedWith { get; private set; }
public override bool TestCollision(Entity e)
{
if (BoundingBox.Intersects(e.GetComponent<Collision>().BoundingBox))
{
PerColorCollision ppc = e.GetComponent<PerColorCollision>();
//Get the area of intersection
var intersection = new Rectangle();
intersection.Y = Math.Max(BoundingBox.Top, ppc.BoundingBox.Top);
intersection.Height = Math.Min(BoundingBox.Bottom, ppc.BoundingBox.Bottom) -
intersection.Y;
intersection.X = Math.Max(BoundingBox.Left, ppc.BoundingBox.Left);
intersection.Width = Math.Min(BoundingBox.Right, ppc.BoundingBox.Right) -
intersection.X;
foreach (var color in Colors)
{
for (int y = intersection.Y; y < intersection.Bottom; y++)
{
for (int x = intersection.X; x < intersection.Right; x++)
{
//We subtract our bounding boxes to set the position back to relative, since the area of intersection would be the at the absolute positions
Color color1 = ColorData[(x - BoundingBox.Left), (y - BoundingBox.Top)];
Color color2 =
ppc.ColorData[
(x - ppc.BoundingBox.Left),
(y - ppc.BoundingBox.Top)];
if (color1.A != 0 && color2 == color)
{
ColorsColliedWith.Add(color);
break;
}
}
if (ColorsColliedWith.Contains(color))
break;
}
}
}
if (ColorsColliedWith.Count > 0)
return true;
return false;
}
public override void Update()
{
ColorsColliedWith.Clear();
base.Update();
}
In the base.Update it runs the TestCollision method against all of the partners in Collision.Partners. Is there any other optimization that I can do?