Per Pixel Collision - Could do with some general tips

痴心易碎 提交于 2019-12-11 10:09:23

问题


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 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.)



来源:https://stackoverflow.com/questions/14894796/per-pixel-collision-could-do-with-some-general-tips

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!