1

我正在尝试绘制两条平行线。我可以画一条线,但是当我去画第二条线时,没有人画。不知道为什么。

我有一个看起来像这样的 Line 类:

    #import "Line.h"

    static GLKBaseEffect *effect;

    @implementation Line

    typedef struct {
        GLKVector3 positionCoordinates;
        GLKVector4 colorCoordinates;
    } VertexData;

    VertexData unitLine[] = {
    //{ { position x,   position y, position z}, {red, blue, green, alpha} }
        { { -0.5f,  0.0f,  0.0f}, {0.0f, 0.0f, 1.0f, 1.0f} },
        { {  0.5f,  0.0f,  0.0f}, {0.0f, 0.0f, 1.0f, 1.0f} }
    };

    - (id) initWithEffect:(GLKBaseEffect *) effect {

    if (self = [super init]) {

        self.effect = effect;

        glGenVertexArraysOES(1, &_vertexArray);
        glBindVertexArrayOES(_vertexArray);

        glGenBuffers(1, &_vertexBuffer);
        glBindBuffer(GL_ARRAY_BUFFER, _vertexBuffer);
        glBufferData(GL_ARRAY_BUFFER, sizeof(unitLine), unitLine, GL_STATIC_DRAW);

        glEnableVertexAttribArray(GLKVertexAttribPosition);
        glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), (GLubyte *)0 + offsetof(VertexData, positionCoordinates));
        glEnableVertexAttribArray(GLKVertexAttribNormal);
        glVertexAttribPointer(GLKVertexAttribNormal, 3, GL_FLOAT, GL_FALSE, sizeof(VertexData), (GLubyte *)0 + offsetof(VertexData, normalCoordinates));

        glBindVertexArrayOES(0);

    }

    return self;
}

- (GLuint) getVertexArray
{
    return _vertexArray;
}

- (void) render {
    glClear(GL_COLOR_BUFFER_BIT);
    [self.effect prepareToDraw];
    glDrawArrays(GL_LINES, 0, 2);
}

- (void) update {

}

- (void) tearDown
{
    glDeleteBuffers(1, &_vertexBuffer);
    glDeleteVertexArraysOES(1, &_vertexArray);
}

@end

然后,在 GLKview 中,我尝试像这样绘制这两行:

在 ViewController.m 中,我有这个:

@interface ViewController () {
    GLuint _program, _program1;
    GLint i;
    GLfloat j;

    GLKMatrix4 _modelViewProjectionMatrix;
    GLfloat _model_translate_x;
    GLfloat _model_translate_y;
    GLfloat _model_translate_z;

    Cube *my_cube;
    Line *my_line[20]; // for the grid lines    
}

- (void)viewDidLoad
{
    ...
    for (i=0; i<20; i++) {
        my_line[i] = [[Line alloc] initWithEffect: self.effect];
    }
    ...
}

- (void)glkView:(GLKView *)view drawInRect:(CGRect)rect
{
    ...
    modelViewMatrix =  GLKMatrix4MakeTranslation(_model_translate_x, _model_translate_y, _model_translate_z);
    modelViewMatrix = GLKMatrix4Scale(modelViewMatrix, 10.0, 1.0, 1.0);

    glBindVertexArrayOES( [my_line[0] getVertexArray] ); 
    modelViewMatrix = GLKMatrix4Translate(modelViewMatrix, 0.0f, 0.0f, 0.0f);
    [my_line[0] render];

    modelViewMatrix = GLKMatrix4MakeTranslation(0.0f, 0.5f, 0.0f);
    [my_line[1] render];
}

如果我注释掉最后一行,那么我会得到一行。如果我把它留在里面,我就没有线了。无论哪种情况,我都会收到控制台错误消息 0x0502。我究竟做错了什么?谢谢!

更新:我有在此代码之前绘制的其他对象。迄今为止,这些对象绘制正确。似乎一旦[my_line[0] render]执行,所有其他对象都消失了。我该怎么做才能纠正这个问题?

4

1 回答 1

0

要绘制线条,请调用渲染,并在渲染中清除颜色缓冲区。因此,您之前绘制的所有内容都会消失。

于 2013-11-14T01:55:01.647 回答