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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值