CharacterMovement2D.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { _decorator, Component, Node, Vec2, v2, Prefab, Vec3 } from 'cc';
  2. import { EasyController, EasyControllerEvent } from './EasyController';
  3. const { ccclass, property } = _decorator;
  4. const tempV2 = v2();
  5. @ccclass('tgxCharacterMovement2D')
  6. export class CharacterMovement2D extends Component {
  7. @property
  8. moveSpeed: number = 100;
  9. @property
  10. needRotation:boolean = false;
  11. start() {
  12. EasyController.on(EasyControllerEvent.MOVEMENT, this.onMovement, this);
  13. EasyController.on(EasyControllerEvent.MOVEMENT_STOP, this.onMovementStop, this);
  14. }
  15. private _moveFactor: number = 0;
  16. private _moveDir: Vec2 = v2(1, 0);
  17. public get moveDir():Vec2{
  18. return this._moveDir;
  19. }
  20. public get realSpeed():number{
  21. return this.moveSpeed * this._moveFactor;
  22. }
  23. onMovement(degree, strengthen) {
  24. let angle = degree / 180 * Math.PI;
  25. if(this.needRotation){
  26. this.node.setRotationFromEuler(0, 0, degree);
  27. }
  28. this._moveDir.set(Math.cos(angle), Math.sin(angle));
  29. this._moveDir.normalize();
  30. this._moveFactor = strengthen;
  31. }
  32. onMovementStop() {
  33. this._moveFactor = 0;
  34. }
  35. onDestroy() {
  36. EasyController.off(EasyControllerEvent.MOVEMENT, this.onMovement, this);
  37. EasyController.off(EasyControllerEvent.MOVEMENT_STOP, this.onMovementStop, this);
  38. }
  39. update(deltaTime: number) {
  40. if (this._moveFactor) {
  41. Vec2.multiplyScalar(tempV2, this._moveDir, this.realSpeed * deltaTime);
  42. let pos = this.node.position;
  43. this.node.setPosition(pos.x + tempV2.x, pos.y + tempV2.y, pos.z);
  44. }
  45. }
  46. }