Hello everyone,
For my studies, I have to create a game with a team of novice programmers, like myself. One of the tasks we have to complete is improving collision performance to a point such that 2000 entities can be in the game, while it runs smoothly. At the moment I got it to run smoothly with 1000 entities, if i disable effects and other visual things. To do this, I divided the game into areas of around 400 pixels and let every game entitiy that needs to be checked for collisions calculate in which area(s) it is in right now, using the four corners of their respective collision boxes. Then, the code only checks collisions for entities in the same areas. The code I was using before, checks every pair of entities twice, because i'm using a double foreach loop.
Now, I tried implementing some changes, such that this won't happen, but now the effects of the collision is only seen on one of the entities or not at all.
This is the code for checking collisions, which resides in the BaseLevel class:
protected void CheckCollision()
{
if (checkCollision)
{
HashSet<GameObject> checkedCollisions = new HashSet<GameObject>();
foreach (HashSet<GameObject> objectList in areas.Values)
{
HashSet<GameObject> ObjectList = new HashSet<GameObject>(objectList);
foreach (GameObject thing in ObjectList)
{
if (thing is GameEntity || thing is Item || thing is Rock)
{
checkedCollisions.Add(thing);
foreach (GameObject other in ObjectList)
if (!checkedCollisions.Contains(other) && other != thing)
if (other is GameEntity || other is Item || other is Rock)
thing.fireCollisionEvent(other);
foreach (Island island in islands)
if (island.isColliding(thing))
thing.fireCollisionEvent(island);
}
}
}
}
}
And this is the code for invoking the collision event, which resides in the GameObject class:
internal void fireCollisionEvent(GameObject other)
{
if (other.ID != this.ID && this.getBoundingBox().Intersects(other.getBoundingBox()))
{
this.onCollisionDetected?.Invoke(this, other);
other.onCollisionDetected?.Invoke(other, this);
}
}
In the previous version, every object invoked their own collision event, but then in that scenario, the collision would also need to be checked twice.
Should this code work? Or did I make a mistake that I overlooked?