cocosCreator给几个精灵添加点击事件

开发环境: cocos creator 3.7.2
开发语言: TypeScript
背景: 小白开始学习cocosCreator,在一个场景中有6个相同的精灵,自己需要知道按钮、移动的是哪个精灵。

自己小白一个,记录自己的方法,如果您有更好更简便的方法,欢迎评论区回复,还望各位大佬多多指教


代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Drag')
export class Drag extends Component {
@property({type:Node})
public DragRoll:Node[] =[]; // 挂载的节点,如下图
public touchNum:number = 0; // 记录点的是哪个精灵
start() {

}
onEnable(){
for(let i = 0;i<6;i++){
this.DragRoll[i].on(Node.EventType.TOUCH_START,this._onTouchStart,this);
this.DragRoll[i].on(Node.EventType.TOUCH_MOVE,this._onTouchMove,this);
this.DragRoll[i].on(Node.EventType.TOUCH_END,this._onTouchEnd,this);
}
}
onDisable(){
for(let i = 0;i<6;i++){
this.DragRoll[i].on(Node.EventType.TOUCH_START,this._onTouchStart,this);
this.DragRoll[i].on(Node.EventType.TOUCH_MOVE,this._onTouchMove,this);
this.DragRoll[i].on(Node.EventType.TOUCH_END,this._onTouchEnd,this);
}
}
_onTouchStart(touchEvent){
for (let i=0;i<6;i++){
if (touchEvent.target == this.DragRoll[i]){
this.touchNum = i + 1; //ts的下标从0开始,所以+1
console.log("点击了第几个按钮 = ",this.touchNum)
}
}
}
_onTouchMove(touchEvent){

}
_onTouchEnd(touchEvent){

}
update(deltaTime: number) {

}
}