YaoGan.ts 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import EventName from "../EventName/EventName";
  2. const { ccclass, property } = cc._decorator;
  3. @ccclass
  4. export default class YaoGan extends cc.Component {
  5. @property(cc.Node)
  6. bg: cc.Node = null;//摇杆背景
  7. @property(cc.Node)
  8. joystick: cc.Node = null;//摇杆 也就是中心点
  9. @property(cc.Node)
  10. parent: cc.Node = null;//摇杆和背景的父节点
  11. max_R: number = 70//25;//摇杆移动的最大半径
  12. @property
  13. is_rotation: boolean = true;//角色是否根据摇杆的方向旋转
  14. @property
  15. is_forbidden: boolean = false;//是否禁用摇杆
  16. CurrentDir: cc.Vec2 = null
  17. CurrentPower: number = null
  18. onLoad() {
  19. //绑定事件
  20. //因为摇杆很小,如果给摇杆绑定事件玩家将很难控制,摇杆的背景比较大,所以把事件都绑定在背景上是不错的选择
  21. this.bg.on(cc.Node.EventType.TOUCH_MOVE, this.move, this);//当手指在背景上移动时触发move事件
  22. this.bg.on(cc.Node.EventType.TOUCH_END, this.finish, this);//当手指在目标节点区域内离开屏幕时触发finish事件
  23. this.bg.on(cc.Node.EventType.TOUCH_CANCEL, this.finish, this);//当手指在目标节点区域外离开屏幕时触发finish事件
  24. }
  25. move(event: cc.Event.EventTouch) {//负责移动摇杆 手指移动时调用
  26. if (this.is_forbidden == false) {//如果没有禁用摇杆
  27. let Camera = cc.Camera.main.node.position
  28. let pos = cc.v2(event.getLocationX() + Camera.x, event.getLocationY()+ Camera.y);//获取触点的坐标
  29. let pos_0 = this.parent.convertToNodeSpaceAR(pos);//将一个点转换到节点 (局部) 空间坐标系,这个坐标系以锚点为原点。
  30. if (pos_0.mag() < this.max_R) {//如果触点长度小于我们规定好的最大半径
  31. this.joystick.x = pos_0.x;//摇杆的坐标为触点坐标
  32. this.joystick.y = pos_0.y;
  33. } else {//如果不
  34. let pos = pos_0.normalizeSelf();//将触点归一化
  35. // console.log('pos', pos.x, pos.y)
  36. let x = pos.x * this.max_R;//归一化的触点坐标 × 最大半径
  37. let y = pos.y * this.max_R;
  38. this.joystick.x = x;//给摇杆坐标赋值
  39. this.joystick.y = y;
  40. }
  41. this.CurrentDir = pos_0.normalizeSelf()
  42. this.CurrentPower = (cc.v2(this.joystick.x, this.joystick.y).mag() / this.max_R)
  43. cc.systemEvent.emit(EventName.YaoGanMove, this.CurrentDir, this.CurrentPower);
  44. }
  45. }
  46. finish() {//摇杆弹回原位置
  47. cc.systemEvent.emit(EventName.YaoGanEnd, this.CurrentDir, this.CurrentPower);
  48. //摇杆坐标和移动向量都为(0,0)
  49. this.joystick.position = cc.v3(0, 0);
  50. }
  51. }