zoukankan      html  css  js  c++  java
  • cocos2dx游戏开发——微信打飞机学习笔记(五)——BackgroundLayer的搭建

    一、创建文件~

           文件名:BackgroundLayer.h

                         BackgroundLayer.cpp

           架构就跟前面的一样,我就直接进入正题 啦,而且github有完整代码,欢迎下载~

    二、创建滚动的背景

           为毛要创建滚动的背景呢= =,因为我们要控制飞机,但总得有往前飞的感觉,所以呢~你懂的~

    然后方法就很简单啦,就是用2张图片,当然是上下能对接起来的那种,然后不停的滚那滚就好啦~

    方法呢,首先在.h文件中进行声明

    void moveBackground(float dt);             //滚动图片的函数
    
        Sprite *_background1;                 //背景图片
        Sprite *_background2;

    然后,我们就默默实现下~

    首先在init()中添加~

    _background1 = Sprite::createWithSpriteFrameName("background.png");
        _background1->setAnchorPoint(Vec2::ZERO);
        _background1->setPosition(Vec2::ZERO);
        this->addChild(_background1);
    
        _background2 = Sprite::createWithSpriteFrameName("background.png");
        _background2->setAnchorPoint(Vec2::ZERO);
        _background2->setPosition(Vec2(_background1->getPositionX(), _background1->getPositionY() + _background1->getContentSize().height));
        this->addChild(_background2);

    这样就初始化好那个图片的位置啦啦~

    然后就是关键的滚动的函数~

    void BackgroundLayer::moveBackground(float dt)
    {
        if (_background2->getPositionY() <= 0)
        {
            _background1->setPositionY(0);
        }
        _background1->setPositionY(_background1->getPositionY() - 2);
        _background2->setPositionY(_background1->getPositionY() + _background1->getContentSize().height - 2);
    
    }

    简单吧~,就是一会我们不断的调用这个函数,然后每次调用就让图片往下走,一旦第一张出了屏幕,就立马放回原来的位置,就是这么简单~

    然后就是关键的关键啦~

    this->schedule(schedule_selector(BackgroundLayer::moveBackground), 1.0 / 60);

    别看就之后一行代码~,这是cocos封装好的,要不很麻烦的~,现在会用就好啦,这么写,就是在游戏过程中会以1 /60的间隔调用这个函数,这样子的话,我们人眼看起来就是动画的感觉~,大工告成

    三、最后的最后

           你发现运行后没有反应~,那是因为你还没有加入到Scene中,而且会有很多层,所以我们在GameScene中添加一个函数

    //.h
        void initLayer();
    
        BackgroundLayer *_background;
    //.cpp
    void GameScene::initLayer()
    {
        //add background;
        _background = BackgroundLayer::create();
        this->addChild(_background);
    }

    四~效果图~

    image

  • 相关阅读:
    djongo 前端页面展示自定义api返回的列表数据,并拼接到table上
    ou are trying to add a non-nullable field 'address' to person without a default; we can't do that (the database needs something to populate existing rows).
    python string 类型的公钥转换类型并解密
    Django 禁止访问403,CSRF验证失败,相应中断
    springboot async
    此博客可能不再更新,往后博文将发布在 GitHub 中
    css 中 transition 需要注意的问题
    学习笔记(九)
    微信小程序 drawImage 问题
    学习笔记(八)
  • 原文地址:https://www.cnblogs.com/BlueMountain-HaggenDazs/p/3930958.html
Copyright © 2011-2022 走看看