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

(转载请注明出处: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 value
	if( (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;
}

源代码资源下载地址




  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值