我想让我的顶点数组动态化。这样在每个鼠标事件之后都会添加这些值。当用户拖动鼠标时,我注册鼠标位置坐标。坐标被命名为“loc”。当用户拖动鼠标时,“loc”值会更新。所以我希望当'loc'被更新时,坐标会被添加到顶点数组中。我仍然只能在更新'loc'时这样做,它会重建顶点数组,所以我的顶点数组总是只有一个坐标(当前的'loc'值)。
我的顶点数组值存储在 GLfloat 中:
GLfloat vertexes[] = { loc.x, loc.y };
'loc'- (void) mouseDragged:(NSEvent *)event
由以下人员注册:
loc = [self convertPoint: [event locationInWindow] fromView:self];
顶点数组由以下方式绘制- (void) drawMyShape
:
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 0, vertexes);
glPointSize(30);
glDrawArrays(GL_POINTS, 0, vertexCount);
glFlush();
glDisableClientState(GL_VERTEX_ARRAY);
- (void) drawMyShape
在注册鼠标事件并将它们添加到 GLfloat 后调用- (void) mouseDragged:(NSEvent *)event
:
[self drawMyShape]
当前代码:
在 .h 文件中:
NSMutableArray *vertices;
@property (nonatomic, retain) NSMutableArray *vertices;
在 .m 文件的开头
@dynamic vertices;
在 .m 文件中- (id)initWithCoder:(NSCoder *)coder
vertices = [[NSMutableArray alloc] init];
在 .m 文件中- (void) mouseDragged:(NSEvent *)event
loc = [self convertPoint: [event locationInWindow] fromView:self];
NSValue *locationValue = [NSValue valueWithPoint:loc];
[vertices addObject:locationValue];`
[self addValuesToArray];
在 .m 文件中- (void) addValuesToArray
int count = [vertices count] * 2;
NSLog(@"count: %d", count);
int currIndex = 0;
GLfloat GLVertices[] = {*(GLfloat *)malloc(count * sizeof(GLfloat))};
for (NSValue *locationValue in vertices) {
NSValue *locationValue = [vertices objectAtIndex:currIndex++];
CGPoint curLoc = locationValue.pointValue;
GLVertices[currIndex++] = curLoc.x;
GLVertices[currIndex++] = curLoc.y;
}
它崩溃了
NSValue *locationValue = [vertices objectAtIndex:i];
在日志崩溃后,我看到(删除了日志的某些部分,因为我认为它们并不重要):
sum: 2
*** -[__NSArrayM objectAtIndex:]: index 2 beyond bounds [0 .. 1]
sum: 3
*** -[__NSArrayM objectAtIndex:]: index 3 beyond bounds [0 .. 2]
sum: 4
*** -[__NSArrayM objectAtIndex:]: index 4 beyond bounds [0 .. 3]
sum: 5
*** -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]
sum: 6
(lldb)