2013-03-04 115 views
1

觸摸屏幕,當我創造新的精靈/機構的iOS問題:Box2D的和Cocos2d與精靈和定位

-(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_; 
} 

現在,我已經由followi說明兩個問題這兩個圖像顯示了與精靈的調試繪製。視網膜和非視網膜版本:

retina

non-retina

問題#1 - 你可以在兩個圖像看到,進一步遠離(0,0)的對象,精靈變得更偏離物理體。

問題#2 - 紅圈圖像文件爲60x60(視網膜),白圈爲30x30(非視網膜)。爲什麼它們在屏幕上的大小不同? Cocos2d應該使用點,而不是像素,所以它們不應該是屏幕上的相同大小?

回答

2

而不是硬編碼大小,請使用contentSize。

circle.m_radius = sprite.contentSize.width*0.5f/PTM_RATIO; 

這適用於所有標清和視網膜模式。

您可以使用此風格的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 
+0

關於contentSize - 你的代碼導致非視網膜物理身體之中的大小非視網膜精靈,這是相同的好。然而,儘管約9個圓圈以視網膜模式填充屏幕的寬度,但約18個以非視網膜模式填充屏幕。它應該是每個9,這樣的經驗是相同的。我仍然不明白爲什麼會發生這種情況。在典型的iOS開發中,任何一種模式下的30點半徑都是相同的,只是在視網膜模式下獲得更高的分辨率。 – soleil 2013-03-04 18:49:00

+0

關於同步碼,是否需要手動更新每幀中的定位?我希望能夠在PhysicsSprite中自成一體。換句話說,我在哪裏放置該代碼? – soleil 2013-03-04 18:49:56

+0

對不起,我只用自定義CCSprite與b2body成員和重寫更新功能。你的其他問題然後...... – Guru 2013-03-04 18:55:44