cocos2dx中用动作实现背景无限滚动

cocos2dx-3.1.5中用动作实现背景滚动,cocos2dx都可以使用的

用到的动作其实很简单

  1. MoveBy 因为有反动作
  2. TargetedAction 给指定目标1个动作
  3. Spawn 同时执行
  4. Sequence 动作按照顺序执行
  5. RepeatForever 一直重复执行

如果用定时器,会有画面抖动,因为每帧执行的时间不一样,而我们用动作实现背景滚动只需要关注移动的时间,不需要关注每帧偏移的像素是多少。

头文件

#pragma once

#include "GameSceneManager.h"

#define DEF_ROLL_SPEDD 8
/*
背景滚动
*/
class BackgroundLayer : public Layer
{
public:
    virtual bool init();
    CREATE_FUNC(BackgroundLayer);

    Scale9Sprite* createBackGround(Vec2 pos);
    // 默认背景滚动图片
    static int currBgImageIndex;
    // 滚动速度,值越小速度越快
    static int rollTime;
    void startRollBg();
    void stop();

    bool isFastRoll = false;
};

cpp文件

#include "BackgroundLayer.h"

int BackgroundLayer::rollTime = DEF_ROLL_SPEDD;
int BackgroundLayer::currBgImageIndex = 1;

bool BackgroundLayer::init()
{
    if (!Layer::init())
    {
        return false;
    }

    startRollBg();

    return true;
}

Scale9Sprite* BackgroundLayer::createBackGround(Vec2 pos)
{
    auto background = Scale9Sprite::create(StringUtils::format(BACKGROUND_IMG_NAME, currBgImageIndex));
    background->setScale9Enabled(true);
    background->setContentSize(winSize);
    background->setPosition(pos);
    background->setAnchorPoint(Vec2::ZERO);
    this->addChild(background);

    return background;
}

void BackgroundLayer::startRollBg()
{
    // 创建2张背景图
    Scale9Sprite* bg = createBackGround(Vec2::ZERO);
    Scale9Sprite* bg2 = createBackGround(Vec2(0, winSize.height));
    // 滚动动作
    auto mt = MoveBy::create(rollTime, Vec2(0, -winSize.height));
    auto ta = TargetedAction::create(bg, mt);
    auto ta2 = TargetedAction::create(bg2, mt->clone());
    // 同时执行
    auto spawn = Spawn::createWithTwoActions(ta, ta2);
    // 重复执行,设定位置
    auto rf = RepeatForever::create(Sequence::createWithTwoActions(spawn, CallFunc::create([=]()
    {
        //this->stopAllActions();
        bg->setPositionY(0);
        bg2->setPositionY(winSize.height);
        //log("----");
    })));
    // 当前Layer执行这个Action
    this->runAction(rf);
}

void BackgroundLayer::stop()
{
    this->stopAllActions();
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值