觸摸事件(Touch Event) 在遊戲中是經常使用到的。比如常用移動人物,滑動頁面等等。下面就爲新手們作講解
介紹
-
設置觸摸區域
也就是設置需要觸摸所在node的長寬區域即node屬性中的size,如圖1所示
-
觸摸事件註冊監聽
通過cc.Node類中的on註冊事件來使用的,比如註冊Touch Start 事件
在繼承Component的腳本中
//添加一個Touch Start 事件
this.node.on('touchstart',this.onEventStart,this);
- 觸摸事件取消監聽
如註冊監聽類似,不過不使用on事件,而是使用off事件。
this.node.off('touchstart',this.onEventStart,this);
回調事件
- Start事件 (當手指觸點落在目標節點區域內時回調)
如果你想在觸摸開始時做點事件,就可以監聽此事件。 - Move事件(當手指在屏幕上目標節點區域內移動時)
如果當你想知道移動信息做一些操作時,可監聽此事件。 - End事件(當手指在目標節點區域內離開屏幕時)
如果你是在觸摸區域內鬆開時,會回調此事件。 - Cancel事件(當手指在目標節點區域外離開屏幕時)
如果你是觸摸區域內鬆開時,是不會回調End事件,而回調Cancel事件。
例子
cc.Class({
extends: cc.Component,
properties: {
},
onLoad() {
this.registerEvent();
},
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);
},
init(data) {
},
/**
* 觸摸開始
* @param {*} event
*/
onEventStart(event) {
//世界座標
let worldPoint = event.getLocation();
console.log('start Event \n worldPoint=', 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);
},
update(dt) {
},
onDestroy() {
}
});
最後
希望通過講解,對新手們有所幫助。這是完整Demo。最後還是那句話,喜歡就動動手指點喜歡,關注我吧。我會不定時更新Cocos Creator教程哦~