我在触摸屏幕时创建了新的 Sprite / body :
-(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_;
}
现在,我有两个问题,由以下两张图片说明,它们显示了带有 Sprite 的调试绘制。视网膜和非视网膜版本:
问题 #1 - 正如您在两张图片中看到的那样,物体离 (0,0) 越远, Sprite 就会越远离物理体。
问题 #2 - 红色圆圈图像文件为 60x60(视网膜),白色圆圈为 30x30(非视网膜)。为什么它们在屏幕上的大小不同? Cocos2d 应该使用点而不是像素,所以它们在屏幕上的大小不应该相同吗?
最佳答案
使用 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
关于ios - iOS 上的 Box2d 和 Cocos2d Sprite 和定位问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15208167/