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
float radians = m_pB2Body->GetAngle();
float c = cosf(radians);
float s = sinf(radians);

// Although scale is not used by physics engines, it is calculated just in case
// the sprite is animated (scaled up/down) using actions.
// For more info see: http://www.cocos2d-iphone.org/forum/topic/68990
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;
}


你可能感兴趣的:(cocos2dx)