简体   繁体   中英

b2Body not properly positioned on CCSprite?

I am using Ray Wenderlich's code from here: http://www.raywenderlich.com/606/how-to-use-box2d-for-just-collision-detection-with-cocos2d-iphone

This is the code I am using to add a b2Body/Def/Fixture to my CCSprite:

- (void)addBoxBodyForSprite:(CCSprite *)sprite {
    b2BodyDef spriteBodyDef;
    spriteBodyDef.type = b2_dynamicBody;
    spriteBodyDef.position.Set(sprite.position.x/CTM_RATIO, sprite.position.y/CTM_RATIO);
    spriteBodyDef.userData = sprite;
    b2Body *spriteBody = world->CreateBody(&spriteBodyDef);
    b2PolygonShape spriteShape;
    spriteShape.SetAsBox(sprite.contentSize.width/CTM_RATIO/2, sprite.contentSize.height/CTM_RATIO/2);
    b2FixtureDef spriteShapeDef;
    spriteShapeDef.shape = &spriteShape;
    spriteBody->CreateFixture(&spriteShapeDef);
}

Instead of PTM_Ratio I chose CTM_Ratio. Anyway my b2Bodies are not properly positioned on my CCSprites.

So to be explain my issue I'll say my sprite is 50 pixels wide by 100 pixels tall. It seems like my b2Body on that sprite is like 60 pixels wide by 110 pixels tall.

I know Box2D uses meters but is there any way to PERFECTLY but the b2Body onto my CCSprite maybe by using Pixels?

Thanks!

What is CTM_RATIO? I assume for the moment that it is simply a different value of PTM_RATIO, in which case you could have simply changed the PTM_RATIO value.

The only reason why PTM_RATIO exists is not because Box2D uses meters. It's because Box2D works best with values ranging from 0.1 to 100.0. So any ratio that scales down all position values to within that range and back is fine. You could simply treat Box2D positions as being pixel positions - or more accurately for iOS Devices: point positions. However, that can lead to performance and simulation issues with Box2D, for example penetrating objects and so on. So it is not recommended to not use the PTM_RATIO.

My best guess is that you simply overlooked to change one occurrence of PTM_RATIO with CTM_RATIO, which causes the misalignment. The only other alternative is that you simply made a mistake in calculating respectively scaling the position or sizes of your Box2D objects respectively the sprites that represent the bodies visual appearance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM