一篇文章搞定Cocos Creator开发中的触摸事件和键盘事件
在Cocos Creator游戏开发中,我们经常需要处理事件响应。而其中又以触摸事件和键盘事件使用频率最高,下面我就一起来看下。
一、 触摸事件
1: 触摸事件类型: START, MOVED, ENDED(物体内), CANCEL(物体外);
2: 监听触摸事件: node.on(类型, callback, target(回掉函数的this), [useCapture]);
3: 关闭触摸事件: node.off(类型, callback, target(回掉函数的this), [useCapture]);
4: 移除所有的注册事件:targetOff (target) ;
5: 回调函数的参数设置 function(e(cc.Touch))
6: cc.Touch: 触摸对象,点击链接加入群聊【unity/cocos交流二群】
常用方法getLocation返回触摸的位置;getDelta返回距离上次的偏移;
7: cc.Event: stopPropagationImmediate/stopPropagation 停止事件的传递;
8: 事件冒泡: 触摸事件支持节点树的事件冒泡,会从当前节点往上一层一层的向父节点传送;
如下案例,物体跟随手指触摸移动实现:
编辑

GameMgr.ts代码如下:

编辑
二、 键盘事件
1:cc.SystemEvent.on(type, function, target, useCapture);
type: cc.SystemEvent.EventType.KEY_DOWN 按键按下;
cc.SystemEvent.EventType.KEY_UP 按键弹起;
2: cc.SystemEvent.on(type, function, target, useCapture);
3: 监听的时候,我们需要一个cc.SystemEvent类的实例,我们有一个全局的实例cc.systemEvent,小写开头
3: 键盘回调函数: function(event) {
event.keyCode [cc.KEY.left, ...cc.KEY.xxxx]
案例:按上下左右键,控制红色块的运动。
新建PlayerCtrl.ts,挂载到Red节点上。代码如下:

