Vanarajan
Vanarajan

Reputation: 539

Position in box2d and sprite

I have two type of position in cocos2dx and box2d

There are

CCSprite* parent = CCSprite::create("parent.png");
parent->setPosition(ccp(100, 100));

b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(self.position.x / PTM_RATIO,self.position.y / PTM_RATIO);

What is the difference between these two position

PTM_Ratio have the values 32 or 40.

What is PTM_RATIO and its values?

Upvotes: 0

Views: 1541

Answers (3)

Singhak
Singhak

Reputation: 8896

The PTM_RATIO is 32 in box2d convention

Upvotes: 0

FuzzyBunnySlippers
FuzzyBunnySlippers

Reputation: 3397

There are two coordinate systems at work here:

  1. The box2d coordinate system, which is in meters. All bodies have a position in meters.
  2. The screen coordinate system, which is in pixels. When you want to display a representation of the body (e.g. your sprite) on the screen, you have to use the sprite's setPosition method to place it in pixels.

The PTM ratio is the scale value of pixels/meters that you use to go between the two coordinate systems. Using a straight scale ratio puts the origin of the two coordinate systems right on top of each other. So the position on the screen is just a scale multiple of the position in the box2d world. This means that you won't see bodies with negative coordinates in general (unless part of their sprite sticks over the left edge of the screen).

When you go back and forth between the Box2d world and the screen world, you can use the PTM_RATIO to change the position in one to the position in the other.

Typically, you would set this up as follows:

  1. Create your bodies in positions in the box2d world with a position in just meters.
  2. Create your sprites in the screen system by setting the position based on the body position

For example:

for(all bodies)
{
   Vec2 pos = body->GetPosition();
   _sprite->setPosition(ccp(pos.x*PTM_RATIO,pos.y*PTM_RATIO)); 
}
  1. Apply forces to your bodies and update the physics engine each update(dt) of your application. I suggest using a fixed time step (e.g. 1.0/30.0), but this is a different topic.
  2. Each update(dt) call, update the position of your sprites using the same loop above.

When the user interacts with the screen, you have to convert the touch position to the world position (by dividing by the PTM_RATIO) if you want to find the nearest body, etc.

I have a blog post that talks about this in more detail and shows how to build a "viewport". This allows you to look at a small part of the box2d world and move around the view, scale the objects in it, etc. The post (and source code and video) are located here.

Was this helpful?

Upvotes: 1

Wez Sie Tato
Wez Sie Tato

Reputation: 1186

In box2d you use metres as value of lenght, in cocos2d-x you use pixels or points. PTM is pixels to metres. If PTM_RATIO is 32 it mean that 32 pixels in cocos2d-x is 1 meter in box2d.

Upvotes: 2

Related Questions