背景图像在 Cocos2D 中未正确滚动



我编写了在游戏背景中滚动图像的代码。只需定义两个精灵并设置它们的位置。

CGSize screenSize=[[CCDirector sharedDirector]winSize];
sky1 = [CCSprite spriteWithFile:@"sky1.png"];
sky1.position=ccp(screenSize.width/2, screenSize.height/2);
[self addChild:sky1];
CCLOG(@"sky1 position  width=%f    height=%f",sky1.position.x,sky1.position.y);
sky2=[CCSprite spriteWithFile:@"sky2.png"];
sky2.position=ccp(screenSize.width/2, sky1.position.y+sky1.contentSize.height/2+sky2.contentSize.height/2);
[self addChild:sky2];
[self schedule:@selector(scroll:) interval:0.01f];

并在滚动方法中编写滚动代码:

-(void)scroll:(ccTime)delta{
    CGSize screen=[[CCDirector sharedDirector] winSize];
    CCLOG(@"come from schedule method    pos.y=%f",sky1.position.y);
    sky1.position=ccp(sky1.position.x, sky1.position.y-1);
    sky2.position=ccp(sky2.position.x, sky2.position.y-1);
    if(sky1.position.y <= -([sky1 boundingBox].size.height));
    {
         sky1.position=ccp(sky1.position.x, sky2.position.y+[sky2 boundingBox].size.height);
        CCLOG(@"COMING IN first ifin scroll mwthod  position width=%f  pos.y=%f",sky1.position.x,sky1.position.y);
    }
    if(sky2.position.y<= -[sky2 boundingBox].size.height);
    {
        sky2.position=ccp(sky2.position.x, sky1.position.y+[sky1 boundingBox].size.height);
        CCLOG(@"coming in secnond if ");
    }
}

当我删除if条件时,它可以正常工作一次。我不知道我的状况出了什么问题,我的代码到底是怎么回事。谁能解释一下?

我不太确定为什么你的代码不能正常工作。 我脑海中突然冒出的一个想法是你的间隔可能太短了。 换句话说,0.01f (1/100) 比您的游戏更新速度短,后者很可能是 0.016 (1/60)。 所以我要尝试的第一件事是将您的间隔调整为 0.02f。您还可以从计划调用中删除间隔参数,以便它每帧运行一次。 我也会尝试删除 ccTime 参数,因为它没有被使用。

[self schedule:@selector(scroll)];
-(void)scroll {}

但除此之外,这可能最好使用 CCActions 来处理。 这看起来像是一对简单的CCMoveTo动作与CCRepeatForever相结合,以获得您想要的效果。 这就是我要走的路。

编辑:这是有关使用CCActions完成此操作的更多详细信息。 有多种方法可以做同一件事,但您可以尝试以下一种:

float moveDuration = 3; // or however fast you want it to scroll
CGPoint initialPosition = ccp(screenSize.width/2, screenSize.height/2);
CGPoint dp = ccp(0, -1*sky1.contentSize.height); // how far you want it to scroll down
CCMoveBy *scrollSky1 = [CCMoveBy actionWithDuration:moveDuration position:dp];
CCMoveTo *resetSky1 = [CCMoveTo actionWithDuration:0 position:initialPosition];
CCSequence *sequence = [CCSequence actionOne:scrollSky1 two:resetSky1];
CCRepeatForever *repeat = [CCRepeatForever actionWithAction:sequence];
[sky1 runAction:repeat];

最新更新