0

我想在 OpenGL 中创建一个电闪电。为此,我编写了这个函数:

public Blitz()
{
    points = new float[STEPS * 3];

    for(int i = 0; i < STEPS; i += 3)
    {
        points[i]     = (float) (startX + i * (endX - startX) / STEPS);
        points[i + 1] = (float) (startY + i * (endY - startY) / STEPS);
        points[i + 2] = 0;
    }

    // ...
    vertexBuffer.put(points);
    vertexBuffer.position(0);

}

public void update()
{
    for(int i = 0; i < STEPS; i += 3)
    {
        float rnd = random(); // creates rnd float

        if(points[i] + rnd < startX + 5 && points[i] + rnd > startX - 5)
        {
            points[i] += rnd;
        }
    }

    vertexBuffer.clear();
    vertexBuffer.put(points);
    vertexBuffer.position(0);
}

public void render()
{
    texture.bind();

    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);

    gl.glLineWidth(10);
    gl.glDrawArrays(GL10.GL_LINE_STRIP, 0, STEPS);
}

这是我用于纹理的纹理类:

public class Texture 
{
    private GL10 gl;

    FloatBuffer texCoords;
    private int textureID;

    public Texture(GL10 gl, Bitmap bmp)
    {   
        this.gl = gl;

        int[] TextureIDs = new int[1];
        gl.glGenTextures(1, TextureIDs, 0);     
        textureID = TextureIDs[0];

        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);
        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, GL10.GL_RGBA, bmp, 0);

        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);

        ByteBuffer buffer = ByteBuffer.allocateDirect( 4 * 2 * 4 );
        buffer.order(ByteOrder.nativeOrder());
        texCoords = buffer.asFloatBuffer(); 
        texCoords.put(0);
        texCoords.put(0);

        texCoords.put(0);
        texCoords.put(1);

        texCoords.put(1);
        texCoords.put(1);

        texCoords.put(1);
        texCoords.put(0);       
        texCoords.rewind();
    }

    public void bind()
    {   
        gl.glEnable(GL10.GL_BLEND);
        gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_SRC_ALPHA);

        gl.glEnable(GL10.GL_TEXTURE_2D);
        gl.glBindTexture(GL10.GL_TEXTURE_2D, textureID);
        gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, texCoords);
    }

    public void dispose()
    {
        int[] textures = {textureID};
        gl.glDeleteTextures(1, textures, 0);
        textureID = 0;              
    }
}

使用正常的颜色一切都很好,但如果我想把这个纹理放在线条上,它会得到这个结果:

电纹理 结果

你有什么想法为什么?我的错误是什么?

4

1 回答 1

2

您的错误是,您假设,OpenGL 线将能够绘制一个具有垂直于线方向变化的坐标的纹理。OpenGL 根本无法做到这一点,因为纹理坐标是顶点属性,一条线段只有两个顶点。这意味着,任何纹理坐标变化都只能沿着这条线,而不是垂直于它。

解决方案不是画一条线,而是一条四边形或三角形条带,其顶点被拉伸到线的两侧。使用在屏幕平行空间中运行的着色器最容易做到这一点。

于 2013-10-10T00:10:00.373 回答