2012-08-01 62 views
0

正如Box2D手冊中所建議的,我將body-> userData設置爲與其關聯的CCSprite。但是,當我稍後嘗試訪問它時(即使在同一個方法中,或者在同一個循環中),它不可避免地會拋出EXC_BAD_ACCESS。EXC_BAD_ACCESS嘗試訪問Box2D主體UserData

該錯誤顯示了出現以下代碼結構的任何時間:

b2BodyDef bodyDef; 
b2Body* blockBody; 
Block* block; 

//... 

block = [Block spriteWithFile:spriteName]; 

//Block configuration 
block.position = CGPointMake(x.floatValue * BLOCK_SIZE_PIXELS, y.floatValue * BLOCK_SIZE_PIXELS);   
block.anchorPoint = CGPointZero; 
[self addChild:block z:7]; 
[self.blockArray addObject:block]; 

//Body configuration 
bodyDef.type = b2_dynamicBody; 
bodyDef.position = toMeters(block.position); 
bodyDef.angle = 0.0f; 
bodyDef.linearDamping = 1.0f; 
bodyDef.angularDamping = 0.0f; 
bodyDef.gravityScale = 1.0f; 
bodyDef.allowSleep = true; 
bodyDef.awake = true; 
bodyDef.fixedRotation = true; 
bodyDef.userData = █ 

blockBody = world->CreateBody(&bodyDef); 

vertices[0] = toMeters(CGPointZero); 
vertices[1] = toMeters(CGPointMake(BLOCK_SIZE_PIXELS, 0)); 
vertices[2] = toMeters(CGPointMake(BLOCK_SIZE_PIXELS, BLOCK_SIZE_PIXELS)); 
vertices[3] = toMeters(CGPointMake(0, BLOCK_SIZE_PIXELS)); 

blockShape.Set(vertices, 4); 

fixtureDef.shape = &blockShape; 
fixtureDef.density = 1.0f; 
blockFixture = blockBody->CreateFixture(&fixtureDef); 

block.body = blockBody; 


//UPON INVOKING THIS LINE, 
//PROGRAM CRASHES WITH EXCEPTION: EXC_BAD_ACCESS 
Block* test = (__bridge Block*)blockBody->GetUserData(); 

此代碼出現在loadlevel:在GameLayer.m,它從CCLayer繼承。

Block繼承自GameSprite,它定義了.body並繼承自CCSprite。頭文件:

// 
// Block.h 
// 
// Created by [REDACTED] on 7/20/12. 
// Copyright (c) 2012 [REDACTED]. All rights reserved. 
// 

#import <Foundation/Foundation.h> 
#import "GameSprite.h" 
//#import "Constants.h" 

@interface Block : GameSprite 
{ 
// GameSprite* _sprite; 
// int _platformTag; 
} 

+(Block*) blockWithFile: (NSString*) filename; 
+(Block*) blockWithTexture: (CCTexture2D*) texture; 
@end 

// 
// GameSprite.h 
// LegendaryOiramBrothers 
// 
// Created by [REDACTED] on 7/20/12. 
// Copyright (c) 2012 [REDACTED]. All rights reserved. 
// 

#import "CCSprite.h" 
#import "Constants.h" 
#import "Box2D.h" 

@interface GameSprite : CCSprite 
{ 
    b2Body* body; 
} 

- (void) update; 

- (void) setPosition:(CGPoint)position; 
- (b2Vec2) getVelocity; 
- (void) setVelocity:(b2Vec2) vel; 

@property (nonatomic) b2Body* body; 

@end 

從我可以在網上找到,我的問題似乎是一個不正確的自動釋放的地方 - 但我沒有看到那裏的塊將有機會解除分配。結果,我很困惑。

感謝您的幫助。

回答

2

你能發現這一行中的錯誤嗎?

bodyDef.userData = &block; 

您正在分配指針的地址,而不是指針本身。這應該解決它:

bodyDef.userData = block; 
+0

這樣做。那麼,事實證明它是'bodyDef.userData =(__bridge void *)block;',但這是潛在的問題。謝謝〜 – linkhyrule5 2012-08-01 22:53:33