c++ - OpenGL 平铺/ block 传输/裁剪

标签 c++ opengl sdl tiles clipping

在 OpenGL 中,如何从使用 IMG_Load() 加载的图像文件中选择一个区域? (我正在为一个简单 2D 游戏制作图 block map )

我使用以下原则将图像文件加载到纹理中:

GLuint loadTexture( const std::string &fileName ) {

    SDL_Surface *image = IMG_Load(fileName.c_str());

    unsigned object(0);                        
    glGenTextures(1, &object);                 
    glBindTexture(GL_TEXTURE_2D, object);   

    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->w, image->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, image->pixels);

    SDL_FreeSurface(image);
    return object;
}

然后我使用以下内容在我的渲染部分中实际绘制纹理:

glColor4ub(255,255,255,255);                
glBindTexture(GL_TEXTURE_2D, texture);      
glBegin(GL_QUADS);                          
glTexCoord2d(0,0);  glVertex2f(x,y);
glTexCoord2d(1,0);  glVertex2f(x+w,y);
glTexCoord2d(1,1);  glVertex2f(x+w,y+h);
glTexCoord2d(0,1);  glVertex2f(x,y+h);
glEnd(); 

现在我需要的是一个允许我从 GLuint 中选择某些矩形部分的函数我调用loadTexture( const std::string &fileName ) ,这样我就可以使用上面的代码将这些部分绑定(bind)到矩形,然后将它们绘制到屏幕上。类似于:

GLuint getTileTexture( GLuint spritesheet, int x, int y, int w, int h )

最佳答案

继续将整个拼贴画加载到纹理中。然后在渲染几何体时使用 glTexCoord 选择它的一个子集。

glTexSubImage2D 不会有任何帮助。它允许您将多个文件添加到单个纹理,而不是从单个文件创建多个纹理。

示例代码:

void RenderSprite( GLuint spritesheet, unsigned spritex, unsigned spritey, unsigned texturew, unsigned textureh, int x, int y, int w, int h )
{
    glColor4ub(255,255,255,255);                
    glBindTexture(GL_TEXTURE_2D, spritesheet);
    glBegin(GL_QUADS);                          
    glTexCoord2d(spritex/(double)texturew,spritey/(double)textureh);
    glVertex2f(x,y);
    glTexCoord2d((spritex+w)/(double)texturew,spritey/(double)textureh);
    glVertex2f(x+w,y);
    glTexCoord2d((spritex+w)/(double)texturew,(spritey+h)/(double)textureh);
    glVertex2f(x+w,y+h);
    glTexCoord2d(spritex/(double)texturew,(spritey+h)/(double)textureh);
    glVertex2f(x,y+h);
    glEnd(); 
}

关于c++ - OpenGL 平铺/ block 传输/裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7090692/

相关文章:

c++ - 当游戏逐渐变得更快时,如何使反弹高度恒定?

c++ - 不支持 GLSL 330 内核

c++ - 虚表解释

c++ - OpenGL 纹理绑定(bind)到对象

c++ - std::string 和数据对齐

cocoa - 当我使用 OpenGL Core Profile 3.2 时,我的三角形不渲染

math - 乘法矩阵

c++ - 我删除sdl2和opengl是正确的c++吗

c++ - 在 C++ 中将临时变量作为非常量引用传递

python - python 的 GIL 是否会阻止在功能独立的 c++ 库中并行执行?