[英]Alpha value of pixel color and Per-Pixel-Collision using SDL
我正在尝试在我的SDL游戏框架中实现逐像素碰撞。 我在找出表面上特定像素的alpha值(RGBA)时遇到问题。 我正在使用SDL函数来做到这一点。
SDL_GetRGBA(pixelColor, pixelFormat, &red, &green, &blue, &alpha);
游戏崩溃:将要初始化pixelColor变量时,游戏崩溃(请参见代码中的注释)。 看来问题出在* p指针和pixelColor变量,后者后来在SDL_GetRGBA()方法中用作参数。
变量bpp :我得到变量bpp的值108,有时是106,在某些情况下bpp(每像素字节数)是255。但是这些值是完全错误的,不是吗? 每个像素应该为1或2或3或4个字节...( http://wiki.libsdl.org/SDL_PixelFormat )
p:0x00c1e11c {???}
pixelFormat:SDL2.dll!0x6c80d62c {format = 10746688调色板= 0x00a3fb40}
(这些是其他重要变量的值)
这是我获取碰撞检测像素的alpha值的完整功能。 部分内容来自本教程( http://www.sdltutorials.com/sdl-per-pixel-collision )。
int CollisionHandler::GetAlphaXY(SDL_Surface* surface, int x, int y)
{
// get the specific pixel for checking the alpha value at x/y
SDL_PixelFormat* pixelFormat = surface->format;
int bpp = pixelFormat->BytesPerPixel;
Uint8* p = (Uint8*)surface->pixels + y * surface->pitch + x * bpp;
// ! here the game crashes
Uint32 pixelColor = *p;
// get the RGBA values
Uint8 red, green, blue, alpha;
// this function fails, sometimes the game crashes here
SDL_GetRGBA(pixelColor, pixelFormat, &red, &green, &blue, &alpha);
return alpha;
}
我认为代码是正确的,但是当我用于测试的两个对象发生冲突时,出现运行时错误。 当每个像素的碰撞应该引起碰撞时,而不是当矩形碰撞时,程序不会崩溃。
这就是我的Per-Pixel-Collision方法的样子:
bool CollisionHandler::Per_Pixel_Collision(GameObject* obj1, GameObject* obj2)
{
// only do pixel collision if rectangles collide
if (Rect_Collision(obj1, obj2))
{
int top = max(top1, top2);
int left = max(left1, left2);
int bottom = min(bottom1, bottom2);
int right = min(right1, right2);
// from the top to the bottom
for (int y = top; y < bottom; y++)
{
// from the left to the right
for (int x = left; x < right; x++)
{
// if both alpha values are zero -> both pixels transparent
if (GetAlphaXY(obj1->getTexture().getSurface(), x, y) == 0 && GetAlphaXY(obj2->getTexture().getSurface(), x, y) == 0)
{
return false;
}
else
{
return true;
}
}
}
}
}
好吧,我犯的错误是愚蠢的。 游戏崩溃的原因是曲面是空的,曲面的成员也是空的,因为在我处理纹理初始化的Texture类中,我调用了
SDL_FreeSurface()
这就是为什么什么都SDL_FreeSurface()
原因。 pixelFormat,pixelColor值等等,都通过FeeSurface设置为0。 现在我解决了这个问题,我只是想将它写下来给其他可能也犯同样错误的人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.