Cocos2D垂直滚动背景

时间:2011-03-29 14:38:13

标签: xcode background scroll cocos2d-iphone

我有三张图片(320x480),我正试图在我的Cocos2D应用程序中垂直滚动。

在我的初始化方法中,我有以下内容:

//adding background sprites
background = [CCSprite spriteWithFile:@"BG1.png"];
background2 = [CCSprite spriteWithFile:@"BG2.png"];

//position background sprites
background.position = ccp(size.width, size.height/2);
background2.position = ccp(size.width, size.height*2);

//schedule to move background sprites
[self schedule:@selector(scroll:)];

//adding them to the main layer
[self addChild:background z:0];
[self addChild:background2 z:0];

这是我的滚动方法:

-(void) scroll:(ccTime)dt 
{
//move 30*dt px vertically
background.position = ccp(background.position.x, background.position.y - 30*dt);
background2.position = ccp(background2.position.x, background.position.y - 30*dt);

//reset offscreen position
if (background.position.y < 290)
{
    background.position = ccp(480/2, 480);
}else if (background2.position.y < 290)
{
    background2.position = ccp(480/2,480);
}
}

目前正在发生的事情是我的第一张背景图片偏移了大约四分之一的屏幕(水平),它从屏幕底部开始向上四分之一,但它向下滚动。我的第二个背景图像实际上并没有产生,第一个图像只是在偏移时一遍又一遍地循环。有没有办法让两张图像在背景中连续平滑循环,我将如何合并第三张图像?

另外,只是一个快速的问题,用名字中的数字命名对象(我认为它们是对象)是不好的(即background2 / background3)?

1 个答案:

答案 0 :(得分:6)

在横向模式下进行水平滚动测试(你要做的就是将滚动从水平更改为垂直,你应该能够解决这个问题)不要忘记ccposition来自精灵的中间,而不是0, 0透视......:

    CGSize size = [CCDirector sharedDirector].winSize;

    //adding background sprites
    background = [CCSprite spriteWithFile:@"tracktest.png"];
    background2 = [CCSprite spriteWithFile:@"tracktest.png"];
    [background.texture setAliasTexParameters];
    [background2.texture setAliasTexParameters];

    //position background sprites
    background.position = ccp(background.contentSize.height/2,background.contentSize.width/2);
    background2.position = ccp(size.width,0);

    //schedule to move background sprites
    [self schedule:@selector(scroll:)];

    //adding them to the main layer
    [self addChild:background z:0];
    [self addChild:background2 z:0];

-scroll方法:

-(void) scroll:(ccTime)dt 
{
        //move 30*dt px vertically
  if (background.position.x<background2.position.x){
      background.position = ccp(background.position.x - 30*dt,background.contentSize.height/2);
      background2.position = ccp(background.position.x+background.contentSize.width,background2.contentSize.height/2);
  }else{
      background2.position = ccp(background2.position.x- 30*dt,background2.contentSize.height/2);
      background.position = ccp(background2.position.x+background2.contentSize.width ,background.contentSize.height/2);

  }

  //reset offscreen position
  if (background.position.x <-background.contentSize.width/2)
  {
      background.position = ccp(background2.position.x+background2.contentSize.width,background.contentSize.width/2);
  }else if (background2.position.x < -background2.contentSize.width/2)
  {
      background2.position = ccp(background.position.x+background.contentSize.width, background2.contentSize.width/2);
  }
}