想象一下以下场景:您有一组 PNG 格式的 RPG 角色 spritesheet,并且您希望在 OpenGL 应用程序中使用它们。
单独的字符大小(通常)为 16 x 24 像素(即 24 像素高),并且可以为任意宽度和高度,无需留白。有点像这样:
(来源:kafuka.org)
我已经有了代码来确定给定帧索引和大小的基于整数的剪切矩形:
int framesPerRow = sheet.Width / cellWidth;
int framesPerColumn = sheet.Height / cellHeight;
framesTotal = framesPerRow * framesPerColumn;
int left = frameIndex % framesPerRow;
int top = frameIndex / framesPerRow;
//Clipping rect's width and height are obviously cellWidth and cellHeight.
使用 frameIndex = 11, cellWidth = 16, cellHeight = 24
运行此代码将返回一个剪辑矩形 (32, 24)-(48, 48)
假设它是正确的/底部与宽度/高度相对。
实际问题
现在,给定一个剪切矩形和一个用于放置 Sprite 的 X/Y 坐标,我如何在 OpenGL 中绘制它?首选将零坐标放在左上角。
最佳答案
您必须开始在“纹理空间”中思考,其中坐标在 [0, 1] 范围内。
所以如果你有一个 Sprite 表:
class SpriteSheet {
int spriteWidth, spriteHeight;
int texWidth, texHeight;
int tex;
public:
SpriteSheet(int t, int tW, int tH, int sW, int sH)
: tex(t), texWidth(tW), texHeight(tH), spriteWidth(sW), spriteHeight(sH)
{}
void drawSprite(float posX, float posY, int frameIndex);
};
您所要做的就是将顶点和纹理顶点提交给OpenGL:
void SpriteSheet::drawSprite(float posX, float posY, int frameIndex) {
const float verts[] = {
posX, posY,
posX + spriteWidth, posY,
posX + spriteWidth, posY + spriteHeight,
posX, posY + spriteHeight
};
const float tw = float(spriteWidth) / texWidth;
const float th = float(spriteHeight) / texHeight;
const int numPerRow = texWidth / spriteWidth;
const float tx = (frameIndex % numPerRow) * tw;
const float ty = (frameIndex / numPerRow + 1) * th;
const float texVerts[] = {
tx, ty,
tx + tw, ty,
tx + tw, ty + th,
tx, ty + th
};
// ... Bind the texture, enable the proper arrays
glVertexPointer(2, GL_FLOAT, verts);
glTexCoordPointer(2, GL_FLOAT, texVerts);
glDrawArrays(GL_TRI_STRIP, 0, 4);
}
};
关于opengl - 使用 OpenGL 从 spritesheet 渲染 sprite?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1568559/