我正在尝试渲染部分位于屏幕外并旋转的纹理。我无法确定此旋转纹理的 src 矩形。
如果纹理不旋转,有效的简单方法是:
void CollisionObject::renderObject(SDL_Rect viewport)
{
//dstrect is an object position + object max width / height
if (not SDL_HasIntersection(&viewport, &dstrect))
return;
SDL_Rect src = physics::normalizedIntersection(dstrect, viewport);
SDL_Rect dest = physics::normalizedIntersection(viewport, dstrect);
SDL_RenderCopyEx(gRenderer, texture, &src, &dest, body.getRotation(), NULL, SDL_FLIP_NONE);
}
//helper function
SDL_Rect normalizedIntersection(SDL_Rect a, SDL_Rect b)
{
int x = a.x;
int y = a.y;
a.x = 0;
a.y = 0;
b.x -= x;
b.y -= y;
SDL_Rect res;
SDL_IntersectRect(&a, &b, &res);
return res;
}
不幸的是,如果纹理被旋转,这显然是错误的,因为我们的 src 矩形“切割”了纹理的错误部分。
如何确定正确的 src 矩形?
SDL_Intersect 没有返回负值,因此如果我必须在视口之外渲染纹理(即在相机的顶部或左侧),我就无法正确计算目标矩形。这段代码修复了它:
void CollisionObject::renderObject(SDL_Rect viewport)
{
if (not SDL_HasIntersection(&viewport, &dstrect))
return;
SDL_Rect dest = physics::normalizedIntersection(viewport, dstrect);
// SDL_Intersect wont return -x or -y so we have to acoomodate for that
if (dest.h < dstrect.h && dest.y <= 0)
{
dest.y -= (dstrect.h - dest.h);
}
if (dest.w < dstrect.w && dest.x <= 0)
{
dest.x -= (dstrect.w - dest.w);
}
dest.h = dstrect.h;
dest.w = dstrect.w;
SDL_RenderCopyEx(gRenderer, texture, NULL, &dest, body.getRotation(), NULL, SDL_FLIP_NONE);
}