在 SDL 中渲染部分超出屏幕的旋转纹理

问题描述 投票:0回答:1

我正在尝试渲染部分位于屏幕外并旋转的纹理。我无法确定此旋转纹理的 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 矩形?

Objects sticks out of top, so my intersection rectangle has y>0,切割纹理的上部。如果对象没有旋转就可以了

math graphics rendering sdl
1个回答
0
投票

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.