cocos之游戏手柄控制实例
1.场景布置
2. 添加手柄监听器
-
监听事件的变化
由原先的mouse系列的转换为touch系列的- touchstart 触摸按下,相当于 mousedown
2 . touchmove 触摸移动,相当于 mousemove - touchend 触摸抬起,相当于 mouseup
- touchcancel 触摸取消,被其他事件终止,相当于按下了ESC键
- touchstart 触摸按下,相当于 mousedown
-
坐标设定:当触摸按下随推动位置变化(要用世界坐标转换),触摸抬起后回归原位(直接设定0,0坐标默认相对坐标)。
setPosition()设定的为相对父节点的坐标
onTouchMove(e:cc.Event.EventTouch){
// e.getLocation() 为点击的位置,是世界坐标
// 需要把世界坐标转换为本地坐标
let parent=this.node.parent;// 父节点 (圆形底盘)
let pos:cc.Vec2=parent.convertToNodeSpaceAR(e.getLocation());
this.node.setPosition(pos);
}
onTouchCancel(){
this.node.setPosition(cc.v3(0,0,0));
}
3. 将手柄限制在托盘内。使用方位角来定位边缘位置。pos.normalize()方法返回该点相对于(0,0)的(cos, sin),返回Vec2对象。
let parent=this.node.parent;// 父节点 (圆形底盘)
let pos:cc.Vec2=parent.convertToNodeSpaceAR(e.getLocation());
// 该点所在的方位 (cos, sin)
let direction:cc.Vec2=pos.no