我在触摸屏幕时创建新的精灵/身体:
-(void) addNewSpriteAtPosition:(CGPoint)pos
{
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position=[Helper toMeters:pos];
b2Body* body = world->CreateBody(&bodyDef);
b2CircleShape circle;
circle.m_radius = 30/PTM_RATIO;
// Define the dynamic body fixture.
b2FixtureDef fixtureDef;
fixtureDef.shape=&circle;
fixtureDef.density=0.7f;
fixtureDef.friction=0.3f;
fixtureDef.restitution = 0.5;
body-> CreateFixture(&fixtureDef);
PhysicsSprite* sprite = [PhysicsSprite spriteWithFile:@"circle.png"];
[self addChild:sprite];
[sprite setPhysicsBody:body];
body->SetUserData((__bridge void*)sprite);
}
这是我的定位助手:
+(b2Vec2) toMeters:(CGPoint)point
{
return b2Vec2(point.x / PTM_RATIO, point.y / PTM_RATIO);
}
PhysicsSprite是与Box2D一起使用的典型方法,但我将包含相关方法:
-(CGAffineTransform) nodeToParentTransform
{
b2Vec2 pos = physicsBody->GetPosition();
float x = pos.x * PTM_RATIO;
float y = pos.y * PTM_RATIO;
if (ignoreAnchorPointForPosition_)
{
x += anchorPointInPoints_.x;
y += anchorPointInPoints_.y;
}
float radians = physicsBody->GetAngle();
float c = cosf(radians);
float s = sinf(radians);
if (!CGPointEqualToPoint(anchorPointInPoints_, CGPointZero))
{
x += c * -anchorPointInPoints_.x + -s * -anchorPointInPoints_.y;
y += s * -anchorPointInPoints_.x + c * -anchorPointInPoints_.y;
}
self.position = CGPointMake(x, y);
// Rot, Translate Matrix
transform_ = CGAffineTransformMake(c, s, -s, c, x, y);
return transform_;
}
现在,我有两个问题由以下两个图像说明,它们显示了精灵的调试绘制。视网膜和非视网膜版本:
问题#1 - 正如你在两个图像中看到的那样,距离(0,0)对象越远,精灵就越远离物理体。
问题#2 - 红色圆圈图像文件是60x60(视网膜),白色圆圈是30x30(非视网膜)。为什么屏幕尺寸不同? Cocos2d应该使用点,而不是像素,所以它们不应该在屏幕上大小相同吗?
答案 0 :(得分:2)
使用contentSize。而不是硬编码大小。
circle.m_radius = sprite.contentSize.width*0.5f/PTM_RATIO;
这适用于所有SD和Retina模式。
您可以使用此样式在box2d和cocos2d位置之间进行同步:
body->SetTransform([self toB2Meters:sprite.position], 0.0f); //box2d<---cocos2d
//OR
sprite.position = ccp(body->GetPosition().x * PTM_RATIO,
body->GetPosition().y * PTM_RATIO); //box2d--->cocos2d