如何在屏幕上来回移动精灵

时间:2015-01-27 12:44:17

标签: c++ ios animation cocos2d-x

这是一款2D游戏,其中包含沿X轴随机生成的移动平台。我需要将它们水平移动到屏幕上,但当它们到达边缘时,它们将向相反方向移动。并且,为了使游戏不易预测,我想开始沿着远离边缘的方向移动精灵。

如何在Cocos2d-x C ++中实现此效果?

编辑:到目前为止,这是我正在测试的代码,但有一个主要问题,它仅适用于第一个平台。当放置一个新平台时,由于某种原因它会离开屏幕,我不会再看到它。我很确定有更好的方法可以做到,所以,提前感谢您的帮助。

请注意,此代码位于Delta函数内:

void GameScene::step(float dt) {
...

CODE:

for (int p = kPlatformsStartTag; p < kPlatformsStartTag + kNumPlatforms; p++) {
        CCSprite *plat = (CCSprite*)getChildByTag(p);
        CCPoint pos = plat->getPosition();
        CCSize size = plat->getContentSize();

        if(plat->getTag() == kMovingPlatformTag)  {

            if(pos.x > CCDirector::sharedDirector()->getWinSize().width - (size.width /2)  || !isMovingToLeft) {
                pos.x -= 0.7f  * plat->getScaleX();
                isMovingToLeft = (pos.x <= size.width /2  ) ? true : false; //(pos.x <= size.width ) ? true : false;

                //Not allow to move the platform beyond the left edge of the screen
                if(pos.x < 0) {
                    pos.x = size.width /2;
                    isMovingToLeft = true; //Here we force to flip the movement to the opposite direction
                }
                CCLog("1. value of isMovingToLeft : %d", isMovingToLeft);

            }

            if (pos.x >= 0 && isMovingToLeft) { //size.width could be greater that 20 pixels margin
                pos.x += 0.7f  * plat->getScaleX();
                isMovingToLeft = (pos.x >= CCDirector::sharedDirector()->getWinSize().width - (size.width /2) ) ? false : true;

                //Not allow to move the platform beyond the right edge of the screen
                if(pos.x > CCDirector::sharedDirector()->getWinSize().width) {
                    pos.x = CCDirector::sharedDirector()->getWinSize().width  - (size.width /2);
                    isMovingToLeft = false; //Here we force to flip the movement to the opposite direction.

                }
                CCLog("2. value of isMovingToLeft : %d", isMovingToLeft);
            }
//            CCLog("value of pos.x => %f", pos.x);
            plat->setPosition(pos);
        }

    }

0 个答案:

没有答案