本篇教程,我们将介绍 Cocos Creator 的玩家输入事件。
目前支持了以下几种事件:
所有的事件都是通过函数 cc.eventManager.addListener(listener, target)
来进行添加。
可选的 event
类型有:
1. cc.EventListener.MOUSE (鼠标)
2. cc.EventListener.KEYBOARD (键盘)
3. cc.EventListener.TOUCH_ONE_BY_ONE (单点触摸)
4. cc.EventListener.TOUCH_ALL_AT_ONCE (多点触摸)
cc.EventListener.MOUSE
// 添加鼠标事件监听器
var listener = {
event: cc.EventListener.MOUSE,
onMouseDown: function (event) {
cc.log('Mouse Down: ' + event);
},
onMouseUp: function (event) {
cc.log('Mouse Up: ' + event);
},
onMouseMove: function (event) {
cc.log('Mouse Move: ' + event);
}
onMouseScroll: function (event) {
cc.log('Mouse Scroll: ' + event);
}
}
// 绑定鼠标事件
cc.eventManager.addListener(listener, this.node);
cc.EventListener.KEYBOARD
// 添加键盘事件监听器
var listener = {
event: cc.EventListener.KEYBOARD,
onKeyPressed: function (keyCode, event) {
cc.log('keyDown: ' + keyCode);
},
onKeyReleased: function (keyCode, event) {
cc.log('keyUp: ' + keyCode);
}
}
// 绑定键盘事件
cc.eventManager.addListener(listener, this.node);
cc.EventListener.TOUCH_ONE_BY_ONE
注意:onTouchBegan
回调事件里要 return true
, 这样后续的 onTouchEnded
和 onTouchMoved
才会触发事件。
// 添加单点触摸事件监听器
var listener = {
event: cc.EventListener.TOUCH_ONE_BY_ONE,
onTouchBegan: function (touches, event) {
cc.log('Touch Began: ' + event);
return true; //这里必须要写 return true
},
onTouchMoved: function (touches, event) {
cc.log('Touch Moved: ' + event);
},
onTouchEnded: function (touches, event) {
cc.log('Touch Ended: ' + event);
}
onTouchCancelled: function (touches, event) {
cc.log('Touch Cancelled: ' + event);
}
}
// 绑定单点触摸事件
cc.eventManager.addListener(listener, this.node);
cc.EventListener.TOUCH_ALL_AT_ONCE
同理:onTouchesBegan
回调事件里也要 return true
, 这样后续的 onTouchesEnded
和 onTouchesMoved
才会触发事件。
// 添加多点触摸事件监听器
var listener = {
event: cc.EventListener.TOUCH_ALL_AT_ONCE,
onTouchesBegan: function (touches, event) {
// touches 触摸点的列表
cc.log('Touch Began: ' + event);
return true; //这里必须要写 return true
},
onTouchesMoved: function (touches, event) {
cc.log('Touch Moved: ' + event);
},
onTouchesEnded: function (touches, event) {
cc.log('Touch Ended: ' + event);
}
onTouchesCancelled: function (touches, event) {
cc.log('Touch Cancelled: ' + event);
}
}
// 绑定多点触摸事件
cc.eventManager.addListener(listener, this.node);