cc.Class({ extends: cc.Component, properties: { }, onLoad () { this.init(); this.registerEvent(); }, init() { this.firstX = null; this.firsty = null; this.listenerArr = []; this.touchTimes = 0; }, registerEvent() { //touchstart 可以换成cc.Node.EventType.TOUCH_START this.node.on('touchstart', this.onEventStart, this); //touchmove 可以换成cc.Node.EventType.TOUCH_MOVE this.node.on('touchmove', this.onEventMove, this); //touchcancel 可以换成cc.Node.EventType.TOUCH_CANCEL this.node.on('touchcancel', this.onEventCancel, this); //touchend 可以换成cc.Node.EventType.TOUCH_END this.node.on('touchend', this.onEventEnd, this); }, registerListener(listenerNode) { // 要判断对象是否已经注册过,如果存在不注册 if(this.indexOf(this.listenerArr, listenerNode) != -1) return; this.listenerArr.push(listenerNode); }, unRegisterListener(listenerNode) { // 要判断对象是否已经注册过,如果存在才可以删除 if(this.indexOf(this.listenerArr, listenerNode) != -1) { this.remove(this.listenerArr, listenerNode); } }, dispatchEvent(eventName, data)//把所有的监听事件分发给所有接收到回调的节点 { for (let i = 0; i < this.listenerArr.length; i++) { this.listenerArr[i].emit(eventName, data); } }, indexOf(arr, item) {//判断元素在数组第几位 for (let i = 0; i < arr.length; i++) { if (arr[i] == item) return i; } return -1; }, /** * 触摸开始 * @param {*} event */ onEventStart(event) { //世界坐标 let worldPoint = event.getLocation(); // console.log('start Event \n worldPoint=', worldPoint); // console.log('touch start'); this.firstX = worldPoint.x; this.firstY = worldPoint.y; this.touchTimes++; if(this.touchTimes == 2) { this.touchTimes = 0; this.dispatchEvent('doubletouch', worldPoint); } else { this.scheduleOnce(function(){ this.touchTimes = 0; }.bind(this),0.2) } this.dispatchEvent('touchstart', worldPoint); }, /** * 触摸移动 * @param {*} event */ onEventMove(event) { //世界坐标 let worldPoint = event.getLocation(); // console.log('move Move \n worldPoint=', worldPoint); }, /** * 触摸 * 当手指在目标节点区域外离开屏幕时 * 比如说,触摸node的size是200x200。 * 当超过这个区域时,就是触发这个事件 * @param {*} event */ onEventCancel(event) { //世界坐标 let worldPoint = event.getLocation(); // console.log('cancel Event \n worldPoint=', worldPoint); }, /** * 当手指在目标节点区域内离开屏幕时 * @param {*} event */ onEventEnd(event) { //世界坐标 let worldPoint = event.getLocation(); // console.log('end Event \n worldPoint=', worldPoint); let endX = this.firstX - worldPoint.x; let endY = this.firstY - worldPoint.y; // var tempPlayer = node.parent.convertToNodeSpaceAR(touchPoint); // node.setPosition(tempPlayer); if (Math.abs(endX) > Math.abs(endY)){ //手势向左右 //判断向左还是向右 if (endX > 0){ //向左函数 // console.log('left'); this.dispatchEvent('swipe', 'left'); } else { //向右函数 // console.log('right'); this.dispatchEvent('swipe', 'right'); } } else { //手势向上下 //判断手势向上还是向下 if (endY > 0){ //向下函数 // console.log('down'); this.dispatchEvent('swipe', 'down'); } else { //向上函数 // console.log('up'); this.dispatchEvent('swipe', 'up'); } } }, });