## davidsu33的专栏

To be or not to be, It's a problem!!!

# cocos2dx之CCPhysicsSprite

CCPhysicsSprite是基于物理引擎的Sprite，其物理引擎有两种一种是基于BOX2D，一种是基于Chipmunk的，不管是那种，我们所需要掌握的重点有两个，一个是基于物理模型坐标系和Cocos坐标系的比例关系m_fPTMRatio，另外一个是物理模型和cocos的sprite对象的同步。下面请看一下同步过程：

1.在设置cocos坐标的时候同步物理坐标

void CCPhysicsSprite::setPosition(const CCPoint &pos)
{
float angle = m_pB2Body->GetAngle();
m_pB2Body->SetTransform(b2Vec2(pos.x / m_fPTMRatio, pos.y / m_fPTMRatio), angle);
}

2.在更新节点矩阵的时候物理模型同步cocos的Sprite

// returns the transform matrix according the Box2D Body values
CCAffineTransform CCPhysicsSprite::nodeToParentTransform()
{
b2Vec2 pos  = m_pB2Body->GetPosition();

float x = pos.x * m_fPTMRatio;
float y = pos.y * m_fPTMRatio;

if (m_bIgnoreAnchorPointForPosition)
{
x += m_obAnchorPointInPoints.x;
y += m_obAnchorPointInPoints.y;
}

// Make matrix

// Although scale is not used by physics engines, it is calculated just in case
// the sprite is animated (scaled up/down) using actions.
if (!m_obAnchorPointInPoints.equals(CCPointZero))
{
x += ((c * -m_obAnchorPointInPoints.x * m_fScaleX) + (-s * -m_obAnchorPointInPoints.y * m_fScaleY));
y += ((s * -m_obAnchorPointInPoints.x * m_fScaleX) + (c * -m_obAnchorPointInPoints.y * m_fScaleY));
}

// Rot, Translate Matrix
m_sTransform = CCAffineTransformMake( c * m_fScaleX, s * m_fScaleX,
-s * m_fScaleY, c * m_fScaleY,
x, y );

return m_sTransform;
}

#### cocos2d-x 之 CCPhysicsSprite 基于物理引擎的Sprite

2014-06-30 16:59:47

#### Cocos2D-X 2.2.3 使用CCPhysicsSprite

2014-03-27 19:08:10

#### CCPhysicsSprite

2014-05-25 07:08:55

#### chipmunk创建和销毁刚体过程

2014-01-17 10:28:47

#### cocos2D-x初探学习笔记（31）2.1新特性CCPhysicsSprite

2015-07-16 16:46:21

#### 使用CCJumpby()和CCRect时出现的诡异问题，求解答。

2014-03-22 04:50:48

#### cocos2D-x 2.1新特性CCPhysicsSprite

2013-06-14 08:53:58

#### cocos2d-x 3.0加载PhysicsEditor生成plist的加载器并生成CCPhysicsBody

2015-03-18 16:32:00

#### cocos2d批次渲染

2015-01-05 16:22:51

#### cocos2D-x 2.1新特性CCPhysicsSprite

2013-05-09 14:23:28