我正在尝试根据 box2d 中的 b2body 调整精灵的位置和旋转。
创建主体后,我将 userData 属性设置为保存精灵和位置等的主体对象的属性。问题是在勾选方法 b->GetUserData 中永远不会检索我放入其中的对象。你能看出以下有什么问题吗?
这是我的添加播放器方法:
-(void) addPlayerShip
{
CCSpriteSheet *sheet = [CCSpriteSheet spriteSheetWithFile:@"PlayerShip.png" capacity:1];
//Get sprite sheet
CCSprite *sprite = [CCSprite spriteWithSpriteSheet:sheet rect:CGRectMake(0,0,64,64)];
[sheet addChild:sprite];
CGSize screenSize = [CCDirector sharedDirector].winSize;
sprite.position = ccp( screenSize.width/2, screenSize.height/2);
[self addChild:sheet];
// Define the dynamic body.
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(sprite.position.x/PTM_RATIO, sprite.position.y /PTM_RATIO);
bodyDef.angularVelocity=0;
b2Body *body = world->CreateBody(&bodyDef);
b2PolygonShape dynamicTriangle;
dynamicTriangle.m_vertexCount=3;
dynamicTriangle.m_vertices[0].Set(0,-1);
dynamicTriangle.m_vertices[1].Set(1,1);
dynamicTriangle.m_vertices[2].Set(-1,1);
// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape = &dynamicTriangle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.0f;
fixtureDef.restitution=0.0f;
b2Fixture *fixture = body->CreateFixture(&fixtureDef);
b2Vec2 *vector = new b2Vec2;
BodyObject *bodyObject = [[BodyObject alloc] initWithBody:body
andFixture:fixture
andVelocity:vector
andSprite:sprite];
bodyDef.userData = bodyObject;
}
以及在 b->GetUserData 上始终返回 null 的 tick 方法
-(void) tick: (ccTime) dt
{
int32 velocityIterations = 8;
int32 positionIterations = 1;
world->Step(dt, velocityIterations, positionIterations);
//Iterate over the bodies in the physics world
for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
if (b->GetUserData() != NULL) {
//Synchronize the Sprites position and rotation with the corresponding body
GameObject *myObject = (GameObject*)b->GetUserData();
myObject.Sprite.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);
myObject.Sprite.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
}
}
}
最后是 bodyObject
#import "BodyObject.h"
@implementation BodyObject
@synthesize Body;
@synthesize Fixture;
-(id) initWithBody:(b2Body*) body
andFixture:(b2Fixture*) fixture
andVelocity:(b2Vec2*) velocity
andSprite:(CCSprite*) sprite
{
self = [super initWithSprite:(CCSprite*)sprite
andVelocity:(b2Vec2*)velocity];
self.Body=body;
self.Fixture=fixture;
return self;
}
@end
我是 Objective C 的新手,所以如果我做错了什么,请告诉我!
编辑:
我在这里尝试了另一段代码,我似乎能够更进一步。
if I set bodyDef.UserData = sprite;
就在该行之后
bodyDef.position.Set(sprite.position.x/PTM_RATIO, sprite.position.y /PTM_RATIO);
然后 GetUserData 返回精灵。但是,如果我在 addPlayerShip 方法末尾将用户数据设置为精灵,那么它会再次返回 null。精灵/身体对象是否被丢弃在某处?