开发者

How to get the position of a sprite in Box2d in iPhone

Help me out with some sample code for getting the position of a sprite in Box2d in开发者_JS百科 iPhone.


To get the position of a sprite from a box2d bodyDef you would first want to save your sprite in the userData property of the bodyDef.

For example, in a factory method that creates a ball within the physics environment:

    //create the body
    b2BodyDef initBodyDef;

    initBodyDef.type = b2_dynamicBody;
    initBodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);

    //Save the sprite in the userData property of the bodyDef, to access later
    initBodyDef.userData = ballSprite;

    b2Body *body = world->CreateBody(&initBodyDef);

    //Rest of the factory method ............ (i.e. create shape, create fixture)

Then when you want to access the position of the sprite, for example when doing collision detection, you would get the pointer to the sprite within the userData property of the bodyDef:

This would be in the tick method (where collision detection takes place), or whereever you need to get the position of the sprite.

    CCSprite *mySprite = (CCSprite *) bodyDef->GetUserData();

    CGPoint spritePosition = mySprite.position;

In the first line of code above we create a sprite object and call the GetUserData method on our bodyDef, which returns the sprite we saved earlier. Note we have to cast the returned userData or it will return an error. Once we have the sprite saved all we have to do is call the position property on our mySprite pointer. Thats it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜