![](/img/trans.png)
[英]C++ SDL2 Error when trying to render SDL_Texture: Invalid texture
[英]A method to rotate a texture in SDL2, C++
我有一个Texture类,它允许我加载图像并渲染它们。 它具有以下属性:
private:
SDL_Texture *m_texture; ///The actual texture
int m_width; ///Its width
int m_height; ///Its height
我想创建一种将纹理旋转一定角度的方法。 这是我所做的:
void Texture::rotation( SDL_Renderer *renderer, float angle )
{
//Target texture to render to
SDL_Texture *target = SDL_CreateTexture( renderer, SDL_PIXELFORMAT_RGBA4444, SDL_TEXTUREACCESS_TARGET, m_width, m_height );
//Set the target texture for rendering
SDL_SetRenderTarget( renderer, target );
//Render m_texture to the target texture with an angle
SDL_RenderCopyEx( renderer, m_texture, NULL, NULL, angle, NULL, SDL_FLIP_NONE );
//Detach the target texture
SDL_SetRenderTarget( renderer, NULL );
//Save texture
SDL_DestroyTexture( m_texture );
m_texture = target;
}
但是,它不是很有效:
由于多种原因,例如碰撞检测和效率,我不能简单地在渲染时旋转纹理。 那么,我该怎么办呢?
对于1),您需要在源上设置Alpha混合,在目标纹理上设置(IIRC)。
对于2),请考虑源矩形的中心点为原点,并以四个向量指向四个顶点。 这四个点始终是离中心较远的点,因此,如果在旋转纹理后确保它们位于纹理内,则效果很好。 您可以使用以下公式将向量绕z轴旋转角度a(弧度):
x' = cos(a) * x - sin(a) * y
y' = sin(a) * x + cos(a) * y
其中(x; y)是原始矢量,而(x'; y')是旋转矢量。 将此变换应用于所有四个向量,然后选择最小和最大x和y值,您便具有目标纹理的边界。
好吧,实际上,由于有两个平行的向量对,您可以进一步简化计算:您只需要两个不平行的向量,并使用以下公式获得宽度和高度:
w = 2*max(abs(x1', x2'))
h = 2*max(abs(y1', y2'))
这种方法的唯一问题是,如果现在进一步旋转该纹理,则将获得不断增长的帧。 为避免这种情况,您可以记住原始纹理的尺寸,并在随后的任何转换中使用它。
资料来源: lipk
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.