Okay, so I have an enemy class(With rotation, position, texture and so on). I spawn a few enemies on the screen, they move around, but they overlap each other. So I tried to do a collision check between two enemies of the same class. But no matter what method I try, it isn't quite working. The best thing I tried was:
foreach (Enemy enemy1 in enemies)
{
enemy1Pos = new Vector2(enemy1.position.X, enemy1.position.Y)
foreach (Enemy enemy2 in enemies)
{
enemy2Pos = new Vector2(enemy2.position.X, enemy2.position.Y)
if (Vector2.Distance(enemy2Pos, enemy1Pos) < 200)
{
enemy1Pos += new Vector2((float)(enemy1.Speed * Math.Cos(enemy1.Rotation)), (float)(enemy1.Speed * Math.Sin(enemy1.Rotation)));
}
}
}
This is not to exact code, so it might have some mistakes in it. Anyway when i implemented this solution, the enemies were not overlapping so everything was fine on that part. But, they were always moving to the right side of the screen.
I've also looked up flocking etc, but I would like to know, how can I detect collision between 2 objects of the same class?
If enemy1 is equal to enemy2 always will collide. :)
Avoid that....
foreach (Enemy enemy2 in enemies)
{
if (enemy2 == enemy1) continue;
enemy2Pos = new Vector2(enemy2.position.X, enemy2.position.Y)
if (Vector2.Distance(enemy2Pos, enemy1Pos) < 200)
{
enemy1Pos += new Vector2((float)(enemy1.Speed * Math.Cos(enemy1.Rotation)), (float)(enemy1.Speed * Math.Sin(enemy1.Rotation)));
}
}
Foreach is not the best here... you can accomplish the collsion checking in a more efficient way with for:
for (int i = 0; i<enemies.Count-1; i++)
{
var enemy1 = enemies[i];
for (int j=i+1; j<enemies.Count; j++)
{
var enemy2 = enemies[j]
}
This way you avoid self collsion checkings and avoid duplicate checking too.