0

正如 Box2D 手册中所建议的,我将 body->userData 设置为与其关联的 CCSprite。但是,当我稍后尝试访问它时——即使在相同的方法或相同的 for 循环中——它不可避免地会抛出 EXC_BAD_ACCESS。

只要出现以下代码结构,就会出现错误:

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:继承自 CCLayer 的 GameLayer.m 中。

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

从我在网上可以找到的内容来看,我的问题似乎是某个地方的自动释放不正确 - 但我看不出该块有机会在哪里解除分配。结果,我比较糊涂。

谢谢你的帮助。

4

1 回答 1

2

你能发现这一行的错误吗?

bodyDef.userData = &block;

您正在分配指针的地址,而不是指针本身。这应该解决它:

bodyDef.userData = block;
于 2012-08-01T22:19:43.097 回答