2010-03-02 33 views
0

我對Objective-C甚至是C語言都很新穎,因此請耐心等待。我的主要目標是使用glDrawArrays(GL_LINE_STRIP,0,points)顯示我的CGPoints NSMutableArray(通過NSValue);將一個NSValues/CGPoints數組轉換爲一個CGPoint結構體,以便在cocos2d中與glDrawArrays一起使用

我注意到,cocos2d的需要數組指針*poli像這樣(?):

 

void ccDrawPoly(CGPoint *poli, int points, BOOL closePolygon) { ... } 
 

所以我想我的NSMutableArray轉換成C數組,我可以訪問/調試CGPoints就好:

 

NSUInteger count = [points count]; 
id *buffer = malloc(sizeof(NSValue) * count); 
[points getObjects: buffer]; 
for(uint i = 0; i < count; i++) { 
    NSValue *val = buffer[i]; 
    CGPoint p = [val CGPointValue]; 
    NSLog(@"points x %i: %f", i, p.x); 
    /* shows up in the console as: 
    -----------points at 0: 42.000000 
    -----------points at 1: 44.000000 
    ... etc 
    */ 
} 
free(buffer); 
 

但我想在那裏我堅持就是讓他們到一個數據類型,要麼ccDrawPolyglDrawArrays(GL_LINE_STRIP, 0, points)會接受。這顯然是一個結構或東西,但我不知道如何讓他們進入一個結構。

任何幫助將不勝感激!謝謝!

+0

糟糕,我想我知道了... 而不是使用NSMutableArray我現在使用CGPoint * parr;在我的init方法中,連同一個NSUInteger「parr_count」來跟蹤* parr的大小。然後,我像添加普通數組一樣添加CGPoint,如下所示:parr [parr_count] = glloc;我唯一的問題是...我怎麼知道要分配多大,以及我應該在什麼時候釋放這些? (在 - (void)dealloc方法?)謝謝! – taber 2010-03-02 23:19:27

回答

0

這裏是新的代碼我使用的情況下,它可以幫助別人:

 


@interface Blah : CCLayer 
{ 
    CGPoint *parr; 
    NSUInteger parr_count; 
    NSUInteger parr_max; 
} 
@end 

@implementation Blah 

-(id) init 
{ 
    if((self = [super init])) { 
    parr_count = 0; 
    parr_max = 64; 
    parr = malloc(parr_max * 2 * sizeof(CGPoint)); 
    } 
    return self; 
} 

... 

-(void) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event 
{ 
    CGPoint prev_loc = [touch previousLocationInView: [touch view]]; 
    CGPoint prev_glloc = [[CCDirector sharedDirector] convertToGL:prev_loc]; 

    CGPoint loc = [touch locationInView: [touch view]]; 
    CGPoint glloc = [[CCDirector sharedDirector] convertToGL:loc]; 

    if(parr_count >= 2048) { // hard limit of 2048 
    return; 
    } else if(parr_count == parr_max) { 
    parr_max = 2 * parr_max; 
    parr = realloc(parr, parr_max * 2 * sizeof(GLfloat)); 
    } 

    parr[parr_count] = prev_glloc; 
    parr_count += 1; 
    parr[parr_count] = glloc; 
    parr_count += 1; 
} 

... 

-(void) draw 
{ 
    if(parr_count < 2048) 
    ccDrawPoly(parr, parr_count, NO); 
} 

- (void) dealloc 
{ 
    free(parr); 
    [super dealloc]; 
} 

@end 

 

它似乎好工作!如果有人有任何優化或評論,我會很感激,謝謝。

+0

我一定要包含代碼來檢查並確保你不會溢出你的'points'數組。就目前而言,您的代碼容易受到緩衝區溢出的影響。 – 2010-03-03 02:31:21

+0

謝謝戴夫!我更新了代碼,添加了parr_max等等 - 這是否有訣竅?再次感謝。 – taber 2010-03-03 03:03:45

相關問題