opengl - 使用 OpenGL 从 spritesheet 渲染 sprite?

标签 opengl sprite

想象一下以下场景:您有一组 PNG 格式的 RPG 角色 spritesheet,并且您希望在 OpenGL 应用程序中使用它们。

单独的字符大小(通常)为 16 x 24 像素(即 24 像素高),并且可以为任意宽度和高度,无需留白。有点像这样:

Terra, from Final Fantasy VI
(来源: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/

相关文章:

objective-c - 如何在 Cocoa 中移动 Sprite ?

jquery - 在更改背景图像位置时避免看到 'scroll effect' 的技术

javascript - 为什么我的图像没有在 HTML5 Canvas 上绘制?

GWT UiBinder 和图像 Sprite

c++ - 读取 GLSL 文件时获取垃圾字符

c++ - 为什么opengl不显示我的火焰粒子

linux - X11 窗口大小调整卡顿

C++ 文件解析器/stdin 输入——这个算法行得通吗?

java - 使用混合创建多个被黑色包围的透明区域

c++ - Opengl 半透明 Sprite