使用Cocos Creator制作一个十五数字推盘游戏教程3

这一篇我们给数字块添加点击事件并且添加计时器

编辑目标点击事件

1.资源管理器Script目录中双击打开block脚本,添加moveEvent方法,该方法将被点击的数字块的currentIndex(位置序号)与Global.emptyIndex(空格子序号)进行比较
如果两者的差值是1(代表空格子在被点击数字块的右侧)或者-1(代表空格子在被点击数字块的左侧)或者-4(代表空格子在被点击数字块的上方)
或者4(代表空格子在被点击数字块的下方),则将被点击方块移动到空格子的位置,同时交换currentIndex与Global.emptyIndex的值

1
2
3
4
5
6
7
8
9
10
moveEvent: function(event){
var target = event.target;
let currentIndex = target.currentIndex,emptyIndex = Global.emptyIndex;
if((emptyIndex - currentIndex) === 1 || (emptyIndex - currentIndex) === -1 || (emptyIndex - currentIndex) === 4 || (emptyIndex - currentIndex) === -4){
var moveAction = cc.moveTo(0.5,Global.positions[emptyIndex].x,Global.positions[emptyIndex].y);
this.node.runAction(moveAction);
Global.emptyIndex = currentIndex;
target.currentIndex = emptyIndex;
}
}
  1. 事件绑定
    资源管理器中双击block预制,将右侧属性检查器Click Events 0改为1,层级管理器block节点拖拽到[0]的第一空,第二空选择block,第三空选择moveEvent
    点击场景编辑器中保存按钮,然后点击关闭按钮

    3.预览项目
    点击空格子相邻数字块,数字块移动到空格子的位置

添加计时器

  1. 添加Label节点
    层级管理器在Canvas结点下新建两个Label节点,一个命名为timeDisplay,string属性设置为 “用时:”,另一个命名为time,string属性设置为 “0s”.
  2. 脚本添加属性
    打开MainScript脚本,添加下面的代码
    1
    2
    3
    4
    5
    6
    7
    properties: {
    ...
    timesDisplay: {
    default: null,
    type: cc.Label
    }
    },

3.节点绑定属性
层级管理器,选择Canvas节点,然后将time结点拖拽到属性检查器的Times Display属性中
4.编辑计时逻辑
打开MainScript,添加下面的代码

1
2
3
4
5
6
7
8
9
10
onLoad () {
...
this.times = 0;
this.schedule(this.updateOne,1);
},
updateOne: function(dt){
this.times += 1;
this.timesDisplay.string = this.times.toString() + 's';
},

预览游戏看一下计时效果

下一篇我们为游戏添加开始及结束场景