cocos creator项目实战【滚动的数字】教程

2019-07-13  本文已影响0人  游戏开发大表哥

待完善,实现多位数的滚动效果)

x的ccc引擎的label组件已经自带简单的数字滚动效果,准备自定义字体配合label,详情可查看官方的吃星星案例,下面主要讲自己代码实现的滚动效果

自己代码实现的滚动效果

1、 准备0~9的素材

2、 滚动的数字,数字需要连接起来,可是我们只能显示一个数字范围,所以我们要把其他的数字裁剪掉

3、 9—>0的时候,我们需要9-->0,所以需要2个0~9相连接

4、 写代码四部曲

  a)      新建一个代码文件,à编辑器自动生成一个模板(组件类

  b)      组件类->实例化(new类)->挂到我们的节点上->组件实例一定要挂到节点上,才可以被使用

  c)      组件实例的固定接口

                 i.          Obj.start()开始运行前调用  obj.update(dt) 每次刷新时

        dt距离上一次update过去的世界

        组件类属性列表,定义组件实例属性的,在这个列表定义的属性,都会被绑定到我们的编辑器

思路

1、准备素材 rolling组件 = 数字图片+content(layout布局、锚点0.5 1)+mask遮罩

2、获得一个数字的高度item_height = content.height / 20

  获取初始位置start_pos = item_height * 0.5

  初始化当前值now_value = 0

  初始化当前content位置为start_pos

3、set_value(value) 直接设置到该位置

    now_value = value;

    content.y = start_pos + now_value * item_height

4、rolling_to(value)

      4 -> 5  4 -> (9) -> 2

      移动单位Value = end < begin ?  end + 10 – begin : end – begin

      移动距离move_s = value * item_height

      根据设置的速度得出移动的时间 time = move_s / this.speed

      使用moveTo方法,在time时间内,content从当前位置滚动到content.y + move_s

 (为了使停止的时候更柔和,给moveTo对象加一个缓动动画m.easing(cc.easeCubicActionOut())

      Endfunc 当滚动到第二条停止后,进行标记,在endfunc里把结束后的content坐标设置为第一条的相应坐标,方便循环使用

  cc.sequence([m, end_func]);   cc.sequence(m, end_func);在使用时没有区别

// rolling_num2.js 滚动实现代码

cc.Class({

    extends: cc.Component,

    properties: {

        speed: 500,

        content: {

            type: cc.Node,

            default: null

        }

    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start() {

        if (this.is_scrolling) {

            return;

        }

        this.item_height = this.content.height / 20;

        this.start_pos = this.item_height * 0.5;

        this.now_value = 0;

        this.content.y = this.start_pos;

        this.set_value(2);

        this.rolling_to(1);

    },

    set_value(value) {

        if (value < 0 || value > 9) {

            return;

        }

        this.now_value = value;

        this.content.y = this.start_pos + value * this.item_height;

    },

    rolling_to(value) {

        if (value < 0 || value > 9) {

            return;

        }

        this.is_scrolling = true;

        value = this.now_value > value ? value + 10 : value;

        var move_s = (value - this.now_value) * this.item_height;

        var time = move_s / this.speed;

        var m = cc.moveTo(time, 0, this.content.y + move_s);

        m.easing(cc.easeCubicActionOut());

        var end_func = cc.callFunc(function() {

            this.now_value = (value >= 10) ? (value - 10) : value;

            if (value >= 10) {

                this.content.y -= 10 * this.item_height;

            }

            this.is_scrolling = false;

        }.bind(this));

        var seq = cc.sequence(m, end_func);

        this.content.runAction(seq);

    },

    // update (dt) {},

});点击链接加入群聊【cocos/unity交流群】

上一篇下一篇

猜你喜欢

热点阅读