0

我想用 CCMove 移动身体我正在使用下面的代码它就像一个平板我想将它从 1px 移动到 100px 然后从 100px 移动到 1px 如果我只从 1x 移动到 100px 它工作正常但它的行为出乎意料当我搬回来

void MovableBlock::update(float dt) {

    b2Vec2 position;

    if(isForward) {
        positionAnimationImg =  ccpAdd(positionAnimationImg, animatableImage->getPosition());
        position = point_to_vec(ccp(this->getPositionX()+positionAnimationImg.x,this->getPositionY()));
    }
    else {

        positionAnimationImg =  ccpSub(positionAnimationImg, animatableImage->getPosition());
        position = point_to_vec(ccp(positionAnimationImg.x-this->getPositionX(),this->getPositionY()));
    }
     CCLog("%f:%f",this->getBody()->GetTransform().p.x,position.y);
    //CCLog("position>>  %f:%f",position.x,position.y);

    this->getBody()->SetTransform(b2Vec2(position.x,
                                         position.y),
                                  this->getBody()->GetAngle());
    animatableImage->setPosition(CCPointZero);
}
4

1 回答 1

1

如果您想将 CCMove 与 Box2d body 一起使用,那么您将 ccsprite 与 body 连接起来,并将 ccmove 应用于 sprite 并根据更新方法中的 sprite 位置变换 body。

示例:在 Cocos@dx

PTM_RATIO 32;

CCSprite *ball = CCSprite::create("icon.png");
ball->setPosition(ccp(visibleSize.width/5, visibleSize.height/5));
this->addchild(ball);

b2BodyDef bdf ;
bdf.type = b2_dynamicBody;
bdf.position.Set((float)(visibleSize.width/(10*PTM_RATIO)), (float)(visibleSize.height/PTM_RATIO));
b2body hero = _world->CreateBody(&bdf);
hero->SetUserData(ball);

CCMoveBy *action = CCMoveBy::create(.5, CCPointMake(ball->getPositionX(), ball->getPositionY()-10));
CCMoveBy* action_back = (CCMoveBy*)action->reverse();
ball->runAction(CCSequence::create(action, action_back, NULL));

现在在更新方法中

CCSprite *sp1 = (CCSprite*)hero->GetUserData();
hero->SetTransform(b2Vec2(sp1->getPositionX()/PTM_RATIO, sp1->getPositionY()/PTM_RATIO), 0);
于 2013-11-14T10:17:38.490 回答