this site has been really amazing for helping me with game development however I'm unable to find an answer for the following question (nor am I able to solve it on my own).
I am trying to do rectangle collision in my game开发者_如何学编程. My idea is to 1) get the original collision bounding rectangle 2) Transform the texture (pos/rot/scale) 3) Factor changes of item into a matrix and then use this matrix to change the original collision bounds of the item.
However, my textures contain a lot of transparency, transparency that affect the overall height/width of the texture (I do this to maintain power of two dimensions).
My problem: How to create a rectangle that forms dimensions which ignore transparency around the object. A picture is provided below:
I guess you could step through each row of pixels in the bounding rectangle, starting from the top, checking when you first hit a pixel with colour by checking its alpha value (Color.A != 0).
That way you'll get Y coordinate of the rectangle.
Then step through each column starting from the left of the bounding rectangle, looking for the first coloured pixel.
You'll get the X this way.
Then step through each row again but starting from the bottom and you'll get the height. Then step through each column again but starting from the right and you'll get the width.
Hope that helps
I think dois answer is the way to do it. I use the following code to find the pixel value at a specific point inside my texture. You can change this code to get line by line the pixels, check for transparency and stop when you find a line with a pixel which is not transparent.
Color[] colorData = new Color[1];
Texture2D texture = //Get your Texture2D here
texture.GetData<Color>(0, new Rectangle(targetPoint.X, targetPoint.Y, 1, 1), colorData, 0, 1);
To check if pixel is not transparent I do this :
if(colorData[0].A > 0)
I don't know how expensive can this operation be for collision detection though.
I know for my games, I use circles. If your objects are reasonably round, it can often provide a closer estimate AND collision detection is dead easy. If the distance between the centres of the objects is less than the sum of the radii, then they are colliding.
If circles are out of the question, then muku or Dois have provided decent answers.
精彩评论