CocosCreator背景图循环播放

时间:2020-04-25
本文章向大家介绍CocosCreator背景图循环播放,主要包括CocosCreator背景图循环播放使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

以前在玩小游戏的时候发现有的小游戏背景图一直再动,视觉效果挺好,给人一种炫炫的感觉,让我这写后台的码农很是羡慕和膜拜。没想到天意弄人,我也开始写游戏前端了刚接触CocosCreator,好多东西都不懂,整个懵逼状态,然后只能硬着头皮上来写,其实写代码思路还是有的,就是api和工具用起来有点陌生。这不,下午有个前端大佬让我弄个游戏背景图循环播放功能,说是游戏里会用到,然后就撸起袖子开干了。

大致思路:
1. 既然是至少轮播得有两张图吧
2. 轮播是肯定是要修改坐标的,横播就是改X坐标,竖播就是改y坐标
3. 循环播就是一张播放完毕,得重新修改它的坐标等待下次播放
算了,直接点还是直接来代码吧。

  1. 在资源管理器新建一个TypeScript文件,重命名为Game,然后把Game文件拖到层级管理器的Cavas下面。Game内容如下:
const {ccclass, property} = cc._decorator;

@ccclass
export default class Game extends cc.Component {
    @property({displayName: '播放速度'})
    speed: number = 0; // 移动时控制速度的变量
    @property({displayName: '播放方向0横1竖'})
    orient: number = 0;// 0横 1竖
    @property( {displayName: '背景图', type: cc.Node})
    bgArr: cc.Node[] = []; // 用于管理背景图片结点的数组,记得回cocos面板中添加数组的结点数量
    
    curBg: cc.Node = null;// 当前播放背景
    nextBg: cc.Node = null;// 即将播放背景
    curIndex: number = 0;// 当前播放背景索引
    xy:string = 'x';// x | y
    wh:string = 'w';// 宽高
    // 是否可以播放
    move:boolean = true;

    start () {
        if (this.bgArr.length == 0) {
            this.move = false;
            return;
        }

        // 如果只有一张背景图,则克隆一个
        if (this.bgArr.length == 1) {
            this.bgArr[1] = cc.instantiate(this.bgArr[0]);
            this.bgArr[0].parent.addChild(this.bgArr[1]);
        }
       
        this.xy = this.orient == 0 ? 'x' : 'y';
        this.wh = this.orient == 0 ? 'width' : 'height';

        this.curBg = this.bgArr[this.curIndex];
        this.nextBg = this.bgArr[this.curIndex + 1];

        // 设置背景图坐标
        this.setBgPosition();
    }
    /**
     * 设置背景图坐标
     */
    setBgPosition () {
        
        this.bgArr[this.curIndex][this.xy] = 0;
        this.bgArr[this.curIndex + 1][this.xy] = - (this.curBg[this.wh] / 2 + this.nextBg[this.wh] / 2);
    }

    update (dt) {
        this.bgMove();
    }

    /**
     * 
     * @param bgList 
     * @param speed 速度
     */
    bgMove() {
        if (this.move) {
            this.curBg[this.xy] += this.speed;
            this.nextBg[this.xy] += this.speed;

            // 当前背景图已播放完
            if(this.curBg[this.xy] >= this.curBg[this.wh]) {
                this.curBg = this.nextBg;
                this.nextBg = this.bgArr[this.curIndex ++ % this.bgArr.length];
                this.nextBg[this.xy] = this.curBg[this.xy] - this.curBg[this.wh] / 2 - this.nextBg[this.wh] / 2;
            }
        }
    }
}

  1. 把要播放的背景图拖入层级管理器的Cavas下面,坐标设置如下图

  2. 给Game脚本属性赋值(把背景图拖入进来),如图

以上就是CocosCreator实现轮播图的一个思路。代码获取

原文地址:https://www.cnblogs.com/rookie-test/p/12774188.html