在OpenGL中制作2D地形的问题

时间:2012-05-04 19:55:27

标签: java opengl libgdx terrain vertex-array

前段时间我问this question有关如何使用opengl顶点制作2D地形的问题。我得到了一个很好的答案,但是在尝试时它没有画任何东西,我无法弄清楚什么是错的,或者如何解决它。

我现在有这个:

public class Terrain extends Actor {

Mesh mesh;
private final int LENGTH = 1500; //length of the whole terrain

public Terrain(int res) {

    Random r = new Random();

    //res (resolution) is the number of height-points 
    //minimum is 2, which will result in a box (under each height-point there is another vertex)
    if (res < 2)
        res = 2;

    mesh = new Mesh(VertexDataType.VertexArray, true, 2 * res, 50, new VertexAttribute(Usage.Position, 2, "a_position")); 

    float x = 0f;     //current position to put vertices
    float med = 100f; //starting y
    float y = med;

    float slopeWidth = (float) (LENGTH / ((float) (res - 1))); //horizontal distance between 2 heightpoints


    // VERTICES
    float[] tempVer = new float[2*2*res]; //hold vertices before setting them to the mesh
    int offset = 0; //offset to put it in tempVer

    for (int i = 0; i<res; i++) {

        tempVer[offset+0] = x;      tempVer[offset+1] = 0f; // below height
        tempVer[offset+2] = x;      tempVer[offset+3] = y;  // height

        //next position: 
        x += slopeWidth;
        y += (r.nextFloat() - 0.5f) * 50;
        offset +=4;
    }
    mesh.setVertices(tempVer);


    // INDICES
    short[] tempIn = new short[(res-1)*6];
    offset = 0;
    for (int i = 0; i<res; i+=2) {

        tempIn[offset + 0] = (short) (i);       // below height
        tempIn[offset + 1] = (short) (i + 2);   // below next height
        tempIn[offset + 2] = (short) (i + 1);   // height

        tempIn[offset + 3] = (short) (i + 1);   // height
        tempIn[offset + 4] = (short) (i + 2);   // below next height
        tempIn[offset + 5] = (short) (i + 3);   // next height

        offset+=6;
    }
}

@Override
public void draw(SpriteBatch batch, float delta) {
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
    mesh.render(GL10.GL_TRIANGLES);
}

这是由Libgdx提供的,它也提供了Mesh类,但这并不是真正相关,因为我相信它工作正常。我的问题在于顶点和索引生成。我也不知道如何调试它,所以任何人都可以看看它,并帮助我找到为什么没有渲染?

1 个答案:

答案 0 :(得分:3)

经过一整天后,我已经尝试了一切来解决它,似乎我忘了索引设置为网格 EM>。

mesh.setIndices(tempIn);  

一条缺失的线,几个小时的痛苦......我是个白痴:)