Hallo,
Ich habe mit Hilfe von einem Tutorial und eigenem basteln eine Methode zur erkennung einer Kollision von 2 texture2D Objekten geschrieben.
Die sieht so aus:
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40:
| protected bool KollisionRechteck(Rectangle a, Rectangle b) { return (a.Right > b.Left && a.Left < b.Right && a.Bottom > b.Top && a.Top < b.Bottom); }
protected bool KollisionSprite(Texture2D a, Vector2 aPos, Texture2D b, Vector2 bPos) { bool kollision = false; Rectangle aRec = new Rectangle((int)aPos.X, (int)aPos.Y, a.Width, a.Height); Rectangle bRec = new Rectangle((int)bPos.X, (int)bPos.Y, b.Width, b.Height); if (KollisionRechteck(aRec, bRec)) { uint[] bitsA = new uint[a.Width * a.Height]; a.GetData<uint>(bitsA); uint[] bitsB = new uint[b.Width * b.Height]; b.GetData<uint>(bitsB);
int x1 = Math.Max((int)aPos.X, (int)bPos.X); int x2 = Math.Min((int)aPos.X + a.Width, (int)bPos.X + b.Width); int y1 = Math.Max((int)aPos.Y, (int)bPos.Y); int y2 = Math.Min((int)aPos.Y + a.Height, (int)bPos.Y + b.Height);
for (int y = y1; y < y2; ++y) { for (int x = x1; x < x2; ++x) { if (((bitsA[(x - (int)aPos.X) + (y - (int)aPos.Y) * a.Width] & 0xFF000000) >> 24) > 20 && ((bitsB[(x - (int)bPos.X) + (y - (int)bPos.Y) * b.Width] & 0xFF000000) >> 24) > 20) { kollision = true; } } } }
return kollision; } |
Ist das so ok, oder habe ich es mir scherer gemacht als es ist?
Wichtig ist, dass durchsichtige Bereiche im Bild nicht als Kollision gewertet werden. Zudem stellt sich mir die Frage, was passiert, wenn ich z.B eine Feind Klasse habe und mir mehrere Objekte davon erzeuge. Wenn ich jetzt einen Spieler habe und auf Kollision mit einem Feind prüfen möchte, dann müsste ich ja in einer Schleife jedes Feindobjekt auf Kollision mit dem Spielerobjekt prüfen.
Kann man das so lösen, oder gibt es da eine bessere/einfachere Methode...