1
votes

I understand the theory behind Per Pixel Collision in Xna, you get the texture data from two textures, and then compare them, checking the alpha values of, for example, your character texture.

What I'm wanting to do is use Per Pixel Collision to check if the Player Sprite has touched the map by checking for collisions with a certain colour (Black). I've tried implementing this before, but the characters always falls through the map with no programming errors thrown. Please point me towards articles/tutorials/videos, or if anybody here could give me some tips and points that would be great too.

1
I realize this is somewhat off-topic, but if you are developing a new game you should know that XNA is "dead": wpcentral.com/xna-dead-long-live-xna. Before you endeavor to create something new, you might want to take a look at MonoGame: monogame.codeplex.com - hross
Would you like to show some of your collision code? - Nico Schertler
I've googled it yes, but most of the articles are quite old and seem a really long winded way of doing it. I'm also sadly aware that Xna is dead :( But I still find it an enjoyable platform. I don't have any code to currently show, I was hoping for some general guidance first, or even a bit of pseudo code before hand, as after many attempts my code never works. - Lewis Wilcock
Here is an example on how to use occlusion queries for pixel perfect collision. Still, I can hardly think of a case were a pixel based collision system is a good choice. How about separating collision from visuals completely by using invisible collision polygons? - Lucius

1 Answers

0
votes

I would not check pixel to pixel between two textures, if I were you. Checking just one point vs a map is not too bad, though;

//In Class-scope:
Color[] CollisionMapData;
Texture2D CollisionMap;

public void LoadContent()  
{  
    CollisionMap = Content.Load<Texture2D>("map");  
    CollisionMapData = new Color[CollisionMap.Width * CollisionMap.Height];  
    CollisionMap.GetData<Color>(CollisionMapData);  
}  

public Boolean Collision(Vector2 position)  
{  
    int index = (int)position.Y * CollisionMap.Width + (int)position.X;

    if (index < 0 || index >= CollisionMapData.Length) //Out of bounds  
        return true;

    if (CollisionMapData[index] == Color.Black)
        return true;

    return false;
}

To check the entire player-sprite against a map, you would have to call the Collision-method for each pixel in the players sprite, creating a vector2 to get the right point. It is a lot easier to check maybe a few points (for instance; topleft, topmiddle, topright, left, right, bottomleft, bottommiddle, bottomright. No need to check middle because sides are already being tested.)