private void InitializeCollisionMapForAnimationKey(BitPixelFieldComponent bitPixelFieldComponent, int animationKey) { var animatedSprite = bitPixelFieldComponent.AnimatedSprite; var animation = animatedSprite.GetAnimation(animationKey); var countAnimationFrames = animation.frames.Count; bitPixelFieldComponent.BitPixelsPerAnimationMap[animationKey] = new List <bool[]>(); bitPixelFieldComponent.TextureWidthPerAnimationMap[animationKey] = new List <int>(); foreach (var animationSubtexture in animation.frames) { var animationSpriteTexture = animationSubtexture.texture2D; var animationTextureBounds = animationSubtexture.sourceRect; var countPixels = animationTextureBounds.Width * animationTextureBounds.Height; var colorField = new Color[countPixels]; animationSpriteTexture.GetData(0, animationTextureBounds, colorField, 0, 1); bitPixelFieldComponent.TextureWidthPerAnimationMap[animationKey].Add(animationSubtexture.sourceRect.Width); var bitField = new bool[countPixels]; for (int i = 0; i < countPixels; ++i) { bitField[i] = (colorField[i].A > 0); } bitPixelFieldComponent.BitPixelsPerAnimationMap[animationKey].Add(bitField); } }
private bool HasCollisionWith(BitPixelFieldComponent first, BitPixelFieldComponent second) { var firstBounds = first.AnimatedSpriteBounds; var secondBounds = second.AnimatedSpriteBounds; int left = (int)Math.Max(firstBounds.Left, secondBounds.Left); int top = (int)Math.Max(firstBounds.Top, secondBounds.Top); int width = (int)Math.Min(firstBounds.Right, secondBounds.Right) - left; int height = (int)Math.Min(firstBounds.Bottom, secondBounds.Bottom) - top; var intersectingRectangle = new Rectangle(left, top, width, height); for (var x = intersectingRectangle.Left; x < intersectingRectangle.Right; x++) { for (var y = intersectingRectangle.Top; y < intersectingRectangle.Bottom; y++) { // NOTE: Sometimes one of the pixel fields is null // TODO: Find out why we have a race condition here if (first.PixelField == null || second.PixelField == null) { return(false); } var componentABit = first.PixelField[(x - (int)firstBounds.Left) + (y - (int)firstBounds.Top) * first.TextureWidth]; var componentBBit = second.PixelField[(x - (int)secondBounds.Left) + (y - (int)secondBounds.Top) * second.TextureWidth]; if (componentABit && componentBBit) { return(true); } } } return(false); }