I am building an XNA game with the following simplified structure:
class Entity
{
Vector3 Speed;
Matrix World;
}
class Mirror : Entity {}
class Lightbeam : Entity {}
class CollisionDetector
{
/*
...
*/
public override void Update(GameTime gameTime)
{
List<Entity> entities = entityManager.level.CurrentSection.Entities;
for (int i = 0; i < entities.Count - 1; i++)
{
for (int j = i + 1; j < entities.Count; j++)
{
if(entities[i].boundingBox.Intersects(entities[j].boundingBox))
{
collisionResponder.Collide(entities[i], entities[j]);
}
}
}
base.Update(gameTime);
}
}
class CollisionResponder
{
public void Collide(Entity e1, Entity e2)
{
Console.WriteLine("Normal entity collision response");
}
public void Collide(Mirror mirror, Lightbeam beam)
{
Collide(beam, mirror);
}
public void Collide(Lightbeam beam, Mirror mirror)
{
Console.WriteLine("Specific lightbeam with mirror collision response");
}
}
What I am trying to achieve is that the Collide(Lightbeam beam, Mirror mirror) method is invoked when the collision detector detects a collision between a beam and mirror (so entities[i] is a Mirror and entities[j] is a Lightbeam and vice versa). However, since the entities list stores objects of the type Entity, the Collide(Entity e1, Entity e2) method is invoked instead.
What i tried to overcome this problem:
- If a collision is detected, check which types of entities are colliding and invoke the corresponding method. This is quite an ugly solution, since the method should be changed each time a new collision type is added.
-
Use generics:
Collide(Entity e1, Entity e2)
where T : Lightbeam
where U : MirrorHowever, this solution doesn’t make the compiler happy.
- I found links to the Builder Pattern and Factory Pattern, but it doesn’t seem like that fixes my problem.
It seems to me that there’s a simple solution to this, but I couldn’t find any on the internet (using combinations of keywords like the following: generics, subclass, method, overloading, list, automatic casting).
You can use the keyword
dynamic.Here is an example:
OUTPUT: