nodeMove.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { EVENT_TYPE, JOY_STATE } from "../../utrl/gameEnum";
  2. import gameEventManager from "../../utrl/gameEventManager";
  3. const { ccclass, requireComponent, property } = cc._decorator;
  4. /**节点移动控制类 */
  5. @ccclass
  6. @requireComponent(cc.RigidBody)
  7. export default class NodeMove extends cc.Component {
  8. @property
  9. /**移动速度 */
  10. move_speed = 200;
  11. @property
  12. /**使用力度 */
  13. use_power = false;
  14. /**当前遥感状态 */
  15. state = JOY_STATE.end;
  16. /**当前遥感角度 */
  17. angle = 0;
  18. /**当前遥感力度 */
  19. power = 0;
  20. /**本身刚体 */
  21. private rigid: cc.RigidBody = null;
  22. onEnable() {
  23. this.state = JOY_STATE.end;
  24. this.angle = 0;
  25. this.power = 0;
  26. this.rigid = this.node.getComponent(cc.RigidBody);
  27. this.rigid.gravityScale = 0;
  28. this.rigid.linearDamping = 5;
  29. this.rigid.fixedRotation = true;
  30. gameEventManager.on(EVENT_TYPE.joy_stick, this.onJoyStick, this);
  31. }
  32. onDisable() {
  33. gameEventManager.off(EVENT_TYPE.joy_stick, this.onJoyStick, this);
  34. }
  35. update() {
  36. this.refreshLinearVelocity();
  37. }
  38. /**
  39. * 遥感回调
  40. * @param state 当前遥感状态
  41. * @param angle 当前遥感角度
  42. * @param power 当前遥感力度
  43. */
  44. private onJoyStick(state: JOY_STATE, angle: number, power: number) {
  45. this.state = state;
  46. this.angle = angle;
  47. this.power = power;
  48. }
  49. /**刷新刚体线性速度 */
  50. private refreshLinearVelocity() {
  51. if (this.state == JOY_STATE.move) {
  52. let rad = this.angle * Math.PI / 180;
  53. this.rigid.linearVelocity = cc.v2(Math.cos(rad), Math.sin(rad)).mul(this.power * this.move_speed);
  54. }
  55. }
  56. }