【Cocosd2d实例教程六】Cocos2d实现屏幕背景的自动滚动

来源:互联网 发布:机柜网络模块接线图 编辑:程序博客网 时间:2024/05/01 12:05

(转载请注明出处:http://blog.csdn.net/buptgshengod

1.介绍

   实现屏幕背景的自动滚动是游戏常遇到的功能,这样我们就不用绘制很长的背景图片,只要设计一张就可以,省时省力。这章将实现这个功能,并把源代码贡献给大家,废话不多说,先上个图,其实是动态的,只是截动态图有点麻烦。

2.代码实现部分

     屏幕的动态滚动主要是一个刷新机制的问题。
第一步,还是进入HelloWorldLayer.h中定义一些节点的对象
#import <GameKit/GameKit.h>// When you import this file, you import all the cocos2d classes#import "cocos2d.h"// HelloWorldLayer@interface HelloWorldLayer : CCLayer <GKAchievementViewControllerDelegate, GKLeaderboardViewControllerDelegate>{        CCParallaxNode *backgroundNode;//这个节点是实现滚动的关键节点
    CCSprite *mainBg;    CCSpriteBatchNode *batchNode;        }// returns a CCScene that contains the HelloWorldLayer as the only child+(CCScene *) scene;@end
第二步当然是来到HelloWorldLayer.m中。
首先来写一下刷新的函数
- (void)updateBackground:(ccTime)dt {    CGSize size = [CCDirector sharedDirector].winSize;        CGPoint backgroundScrollVel = ccp(-size.width, 0);    backgroundNode.position =    ccpAdd(backgroundNode.position,           ccpMult(backgroundScrollVel, dt));    CGSize winSize = [CCDirector sharedDirector].winSize;            NSArray *backgrounds = [NSArray arrayWithObjects:mainBg,nil];    for (CCSprite *background in backgrounds) {        if ([backgroundNode convertToWorldSpace:background.position].x < -background.contentSize.width) {           //if中判断是如果屏幕超出图片范围             backgroundNode.position = ccp(winSize.width*4,0);//图片就以这个速度移动        }    }}
接着,将上一个函数加到update中,实现实时更新。
//实时更新- (void)update:(ccTime)dt {        [self updateBackground:dt];   }
修改init函数
-(id) init{// always call "super" init// Apple recommends to re-assign "self" with the "super's" return valueif( (self=[super init]) ) {CGSize winSize = [CCDirector sharedDirector].winSize;                // 1) 创建 CCParallaxNode视差滚动节点        backgroundNode = [CCParallaxNode node];        [self addChild:backgroundNode z:-2];                // 2) 创建需要添加到CCParallaxNode视差滚动节点的精灵对象                mainBg = [CCSprite spriteWithFile:@"bg.png"];        // 3) 设置云彩的浮动速度 和背景速度               CGPoint bgSpeed = ccp(0.05, 0.05);                        // 4) 将精灵对象添加为CCParallaxNode视差滚动节点的子节点        [backgroundNode addChild:mainBg z:-1                   parallaxRatio:bgSpeed                  positionOffset:ccp(200,winSize.height*0.5)];                 [self scheduleUpdate];//调用update,注意了,这个调用方法很奇特        }return self;}

源代码资源下载地址




原创粉丝点击