zoukankan      html  css  js  c++  java
  • cocos2dx中的实现地图卷动的两种方式

    在游戏当中,实现地图卷动是最基本的功能,具体的实现的方法,大致有两类:

    方法一:加载两张图片,轮流显示,

     优点: 1.无论是地图上下卷动,还是左右卷动都可以

             2.支持各种图片,(png,jpg...)

     缺点: 1.前提是会创建两个背景精灵,稍微浪费内存,

             2.且要求作为背景地图的图片需要大于窗口的大小

    /*
     *给游戏主战斗场景添加滚动的背景地图
     */
    void GameMainScene::addbackground()
    {
        Texture2D* texture = TextureCache::getInstance()->getTextureForKey("groundLevel.jpg");
        _spriteBgH = Sprite::createWithTexture(texture);
        _spriteBgH->setAnchorPoint(Vec2(0, 0));
        _spriteBgH->setPosition(0, 0);
        this->addChild(_spriteBgH);
    
        _lowPos = -_spriteBgH->getContentSize().height;//必须设置地图的下限,且必须使用contentsize(),不能用winSize
        //_lowPos = -winSize.height;//错误
    
        _spriteBgL = Sprite::createWithTexture(TextureCache::getInstance()->getTextureForKey("groundLevel.jpg"));
        _spriteBgL->setAnchorPoint(Vec2(0, 0));
        _spriteBgL->setPosition(0, _lowPos);
        this->addChild(_spriteBgL);
    
        this->scheduleUpdate();
    }
    
    /*
     *帧循环定时器,实现背景地图的卷动
     */
    void GameMainScene::update(float dt)
    {
        _spriteBgH->setPositionY(_spriteBgH->getPositionY() - 2);//地图向下移动的速度
        _spriteBgL->setPositionY(_spriteBgL->getPositionY() - 2);//每帧向下移动2个像素
    
        if (_spriteBgL->getPositionY() < _lowPos)//判断下面的地图是否移出下限
        {
            _spriteBgL->setPositionY(_spriteBgH->getPositionY()+_spriteBgH->getContentSize().height);//如果移出,则直接设置到第一张地图的上面
        }
        if (_spriteBgH->getPositionY() < _lowPos)
        {
            _spriteBgH->setPositionY(_spriteBgL->getPositionY()+_spriteBgL->getContentSize().height);
        }
    }

    方法二:使用Texture2D::TexParams,只需要一张图片,重复绘制,设置textureRect,即可

    优点:1.只需要加载一张图片,更省内存

    缺点:1.需要额外设置textureRect的大小,且支持的图片类型有限(支持部分jpg),png类型的未试过

    /*
     *  卷动背景地图
     */
    void GameMainScene::addMoveBackground()
    {
        xScroll = 0;
        sprite1 = Sprite::create("groundLevel.jpg");//只需要创建一个背景精灵
    
        sprite1->setAnchorPoint(Vec2(0, 0));
        sprite1->setPosition(0, 0);
        addChild(sprite1);
        Texture2D::TexParams texRepeat = { GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_REPEAT };//这些openGL的参数不是对所有的图片类型都适合
        sprite1->getTexture()->setTexParameters(texRepeat);//设置精灵渲染时获得纹理的方式为:重复渲染
        schedule(schedule_selector(GameMainScene::moveBackground), 0.01f);
    }
    /*
    *  通过改变y轴的坐标,实现TextureRect渲染矩形的区域的改变,实现地图卷动的视觉效果
    */
    void GameMainScene::moveBackground(float dt) { sprite1->setTextureRect(Rect(0, (xScroll-=2), winSize.width, winSize.height+10)); //y轴的坐标每帧都递减(向下卷动),如果是递增,则地图向上卷动,如果是x轴坐标变化,则地图左右移动 }
  • 相关阅读:
    h5唤起app
    app唤起的完美解决方案,及阻止浏览器的默认弹窗行为
    cdn
    函数声明和函数表达式的区别
    基础系列(7)—— 结构
    基础系列(4)—— C#装箱和拆箱
    重温软件工程——对软件工程的初步了解
    基础系列(9)—— 抽象方法和接口
    自学系列--git的基础简介
    设计模式之简单工厂模式
  • 原文地址:https://www.cnblogs.com/ttss/p/4136337.html
Copyright © 2011-2022 走看看