4

我正在使用 libGdx 创建一个 2d 游戏,并尝试使用这种特殊方法来绘制一个简单的 2d 纹理,分别指定 4 个顶点;

draw(Texture texture, float[] spriteVertices, int offset, int length)

描述说:使用给定的顶点绘制一个矩形。必须有 4 个顶点,每个顶点由 5 个元素按以下顺序组成:x、y、color、u、v。

其他绘图方法工作正常,但我无法让这个工作。我正在尝试的是这个;

batch.draw(boxTexture, new float[] {-5, -5, 0, Color.toFloatBits(255, 0, 0, 255), 0, 0, 
                5, -5, 0, Color.toFloatBits(255, 255, 255, 255), 1, 0, 
                5, 5, 0, Color.toFloatBits(255, 255, 255, 255), 1, 1, 
                -5, 5, 0, Color.toFloatBits(255, 255, 255, 255), 0, 1}, 3, 3);

我对 OpenGL 的工作原理不是很熟悉,尤其是偏移量和长度应该是多少。有没有更知识渊博的人知道如何让这个工作?

更新:

它使用网格工作,但后来发现没有透明度,这很烦人。最后,我只是为 SpriteBatch 添加了一个自定义方法,只是因为它更容易让我理解。顶点是顺时针绘制的;

public void drawQuad (Texture texture, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float col) {
        if (!drawing) throw new IllegalStateException("SpriteBatch.begin must be called before draw.");

        if (texture != lastTexture) {
            switchTexture(texture);
        } else if (idx == vertices.length) //
            renderMesh();

        final float u = 0;
        final float v = 1;
        final float u2 = 1;
        final float v2 = 0;

        vertices[idx++] = x1;
        vertices[idx++] = y1;
        vertices[idx++] = col;
        vertices[idx++] = u;
        vertices[idx++] = v;

        vertices[idx++] = x2;
        vertices[idx++] = y2;
        vertices[idx++] = col;
        vertices[idx++] = u;
        vertices[idx++] = v2;

        vertices[idx++] = x3;
        vertices[idx++] = y3;
        vertices[idx++] = col;
        vertices[idx++] = u2;
        vertices[idx++] = v2;

        vertices[idx++] = x4;
        vertices[idx++] = y4;
        vertices[idx++] = col;
        vertices[idx++] = u2;
        vertices[idx++] = v;
    }
4

3 回答 3

3

Offset is where in the array to start (for you 0), and length is how many indices the array needs to go through. For your case: 4 points, with 5 pieces of data for each point: 4*5 = 20.

Draw was never starting the render process because the value 3 floats isn't enough to make a triangle (15 is the minimum).

As for P.T.'s answer, this particular function does a fan render, so the correct ordering is either clockwise or counter-clockwise.

Also: The order you put those points and textures in will render the texture upside-down (I don't know if that was intended.)

于 2014-05-12T04:49:01.477 回答
2

偏移量和长度用于获取spriteVertices数组的一部分。0在您的情况下,它们应该是数组.length(将顶点放在局部变量中以计算长度)。

另外,我不确定它是否需要,但我强烈怀疑顶点应该以三角形友好的方式传递。您当前正在执行逆时针枚举。通常对于四边形,您应该使用这样的 Z 模式:

3-4
 \
1-2  

(这是因为 OpenGL 采用列表中的每组 3 个顶点并渲染生成的三角形,因此顶点 1、2、3 和 2、3、4 都应该是有用的三角形。)

于 2012-08-15T18:55:23.690 回答
-2
3-4

 \

1-2*

错了,应该是这样的:

4-3

1-2
于 2015-12-30T20:12:51.247 回答