全局的Touch事件
const{ccclass}=cc._decorator;
@ccclass
export default class GlobalTouchInput extends cc.Component{
private _eventManager=cc["internal"]["eventManager"];
private _touchListener:any;
protected start():void{
super.start();
const EventListener=cc["EventListener"];
this._touchListener=EventListener.create({
event:EventListener.TOUCH_ONE_BY_ONE,
swallowTouches:false,//是否吞噬touch事件
owner:this.node,
mask:null,
onTouchBegan:this.onTouchStart.bind(this),
onTouchMoved:this.onTouchMoved.bind(this),
onTouchEnded:this.onTouchEnded.bind(this),
onTouchCancelled:this.onTouchCancelled.bind(this)
});
this._eventManager.addListener(this._touchListener,this.node);
}
private onTouchStart(touch:cc.Touch,event:cc.Event.EventTouch):boolean{
cc.log("touch start");
//此处必须返回true(表示接触到了节点),否则TOUCH_MOVE,TOUCH_END,TOUCH_CANCEL不触发。
return true;
}
private onTouchMoved(touch:cc.Touch,event:cc.Event.EventTouch):void{
cc.log("touch move");
}
private onTouchEnded(touch:cc.Touch,event:cc.Event.EventTouch):void{
cc.log("touch end");
}
private onTouchCancelled(touch:cc.Touch,event:cc.Event.EventTouch):void{
cc.log("touch cancel");
}
protected onDestroy():void{
super.onDestroy();
this._eventManager.removeListener(this._touchListener,this.node);
}
}
touch穿过透明区域(以下代码未验证)
const {ccclass,property}=cc._decorator;
@ccclass
export default class CrossTransparentTouch extends cc.Component{
protected start():void{
this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd,this)
this.node["_hitTest"]=this.hitTest.bind(this);
}
private hitTest(point:cc.Vec2){
let locationInNode=this.node.convertToNodeSpaceAR(point);
let size=this.node.getContentSize();
let sprite=this.node.getComponent(cc.Sprite);
if(sprite){
//需要在编辑设置 texture.packable 为 false
let imgObj=sprite.spriteFrame.getTexture().getHtmlElementObj();
return this.onLucencyTouch(imgObj, locationInNode.x, size.height-locationInNode.y);
}
return false;
}
private onLucencyTouch(img:HTMLImageElement,x:number,y:number):boolean{
let cvs=document.createElement("canvas");
let ctx=cvs.getContext('2d');
cvs.width=1;
cvs.height=1;
ctx.drawImage(img,x,y,1,1,0,0,1,1);
let imgdata=ctx.getImageData(0,0,1,1);
return imgdata.data[3]>0;
}
private onTouchEnd(eventTouch:cc.Event.EventTouch):void{
console.log("touch end")
}
}