public static CollisionState PerPixelSprite(ISprite sprite1, ISprite sprite2, GraphicsDeviceManager graphics) { int xOffset = 0; int yOffset = 0; int widthOffset = 0; int heightOffset = 0; if (sprite2 is Spaceman) { xOffset = 2; yOffset = 1; widthOffset = -4; heightOffset = -1; } Rectangle rect = new Rectangle((int)(sprite2.GetDestRect().X - sprite1.GetDestRect().X + xOffset), (int)(sprite2.GetDestRect().Y - sprite1.GetDestRect().Y + yOffset), sprite2.GetSpriteWidth() + widthOffset, sprite2.GetSpriteHeight() + heightOffset); return(PerPixel(sprite1, sprite2, rect, graphics)); }
// for rectangular collisions between two sprites. public static bool RectCollisionDetect(ISprite sprite1, ISprite sprite2) { Color[] pixels; int spriteWidth = sprite2.GetSpriteWidth() + (sprite2 is Spaceman? -4 : 0); // because the hitbox on the spaceman should be slightly smaller than it is. int spriteHeight = sprite2.GetSpriteHeight() + (sprite2 is Spaceman ? -1 : 0); Rectangle rect = new Rectangle((int)(sprite2.GetDestRect().X - sprite1.GetDestRect().X + (sprite2 is Spaceman ? 2 : 0)), (int)(sprite2.GetDestRect().Y - sprite1.GetDestRect().Y + (sprite2 is Spaceman ? 1 : 0)), spriteWidth, spriteHeight); // this rectangle represents the space the sprite takes up relative to "this"'s top left corner Rectangle newRect = rect; // newRect is the actual rectangle to check //initial tests to see if the box is even applicable to the object texure being checked if (rect.X + rect.Width <= 0 || rect.Y + rect.Height <= 0) { return(false); } if (rect.X >= sprite1.GetSpriteWidth() || rect.Y >= sprite1.GetSpriteHeight()) { return(false); } // Removes the space on the rectangle that is outside of the bounds of "this"'s texture if (rect.X < 0) { newRect.X = 0; newRect.Width += rect.X; } if (rect.Y < 0) { newRect.Y = 0; newRect.Height += rect.Y; } if (newRect.X + newRect.Width > sprite1.GetSpriteWidth()) { for (int i = 0; i <= sprite1.GetSpriteWidth(); i++) { if (newRect.X + i == sprite1.GetSpriteWidth()) { newRect.Width = i; break; } } } if (newRect.Y + newRect.Height > sprite1.GetSpriteHeight()) { for (int i = 0; i <= sprite1.GetSpriteHeight(); i++) { if (newRect.Y + i == sprite1.GetSpriteHeight()) { newRect.Height = i; break; } } } if (newRect.Width == 0 || newRect.Height == 0) { return(false); } pixels = new Color[newRect.Width * newRect.Height]; sprite1.GetTexture().GetData <Color>( 0, newRect, pixels, 0, newRect.Width * newRect.Height ); for (int y = 0; y < newRect.Height; y++) { for (int x = 0; x < newRect.Width; x++) { Color colorA = pixels[y * newRect.Width + x]; if (colorA.A != 0) { return(true); } } } return(false); }
public static bool CheckMapCollision(int xOffset, int yOffset, ISprite sprite, Map map) { return(MapCollisionDetect(sprite.GetSpriteWidth(), sprite.GetSpriteHeight(), OffsetRect(sprite.GetDestRect(), xOffset, yOffset).ToRectangle(), map)); }