触摸事件:
this.node.on//开启事件
this.node.off//关闭事件
this.node.on(Node.EventType.TOUCH_START,this.onTouchStart,this) ;
this.node.on(Node.EventType.TOUCH_MOVE,this.onTouchMove,this) ;
this.node.on(Node.EventType.TOUCH_ENDthis.onTouchEnd,this) ;
this.node.on(Node.EventType.TOUCH_CANCEL,this.onTouchCancel,this) ;
onTouchStart(event:EventTouch){
Console.log("点击开始");
const uiPos = event.getUILocation();
//设置大小
this.node.setScale(0.9,0.9);
//转化坐标系,由屏幕坐标系转为基于node坐标系
const transform = this.node.getComponent(UITransform);
const nodePos = transform,convertToNodeSpaceAR(uiPos;)
//判断鼠标点击在左侧还是右侧,并使节点移动
If (nodePos.x > 0 ){
this.node.setPosition(this.node.position.x + 50,this.node.position.y);
} else {
this.node.setPosition(this.node.position.x - 50,this.node.position.y);
}
//if else‘优化写法
const dx = nodePos.x > 0 ? 50 : -50;
this.node.setPosition(this.node.position.x + dx,this.node.position.y);
}
onTouchMove(event:EventTouch){
Console.log("点击开始");
const uiPos = event.getUILocation();
--偏移量
//相对于电脑屏幕,会不跟鼠标,实际值
const dx = event.getDeltaX();
const dy = event.getDeltaY();
const pos_x = this.node.position.x;
const pos_y = this.node.position.y;
this.node.setPosition(pos_x + dx,pos_y + dy);
//基于项目屏幕分辨率,实际使用带UI的,逻辑比
const dx = event.getUIDeltaX();
const dy = event.getUIDeltaY();
}
onTouchEnd(event:EventTouch){
Console.log("点击开始");
const uiPos = event.getUILocation();
this.node.setScale(1,1);
}
//cancel,鼠标移到外面,触摸取消时
onTouchCancel(event:EventTouch){
Console.log("点击开始");
const uiPos = event.getUILocation();
this.node.setScale(1,1);
}
//键盘输入事件
Input.on(Input.EventType.KEY_DOWN,this.onKeyDown,this);
onKeyDown(event:EventKeyboard){
Console.log(event);
//判断按下的是哪个建
Console.log(event.keyCode === KeyCode.KEY_W);
}