(待完善,實現多位數的滾動效果)
2.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) {}, });