我想用 CCMove 移动主体,我使用下面的代码,它就像一 block 板,我想将它从 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);
}
最佳答案
如果您想将 CCMove 与 Box2d body 一起使用,那么您可以将 ccsprite 与 body 附加在一起,并将 ccmove 应用于 sprite 并根据更新方法中的 sprite 位置变换 body。
示例:在 Cocos@d-x 中
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);
关于ios - 如何使用 ccmoveto 移动 box2d 主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19955701/