Player.ts 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { BoxCollider2D, CCClass, Collider2D, Component, Contact2DType, IPhysics2DContact, Node, Sprite, SpriteFrame, UITransform, Vec2, _decorator, v2, v3 } from 'cc';
  2. import { GameManager } from '../../Manager/GameManager';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('Player')
  5. export class Player extends Component {
  6. @property(Node)
  7. player: Node = null;
  8. @property(SpriteFrame)
  9. pingmin: SpriteFrame = null;
  10. @property(SpriteFrame)
  11. xiaotou: SpriteFrame = null;
  12. // 移动方向
  13. private _moveDirection: Vec2 | undefined;
  14. private _w: number = 0;
  15. private _h: number = 0;
  16. private sc: number = 1;
  17. onLoad() {
  18. }
  19. start() {
  20. }
  21. public move(direction: Vec2) {
  22. this._moveDirection = direction;
  23. }
  24. public setData(type: string): void {
  25. let x = GameManager.getInstance().getRand(-1, 1);
  26. let y = GameManager.getInstance().getRand(-1, 1);
  27. if (x == 0 ) {
  28. x = 0.5;
  29. }
  30. if (y == 0 ) {
  31. y = 0.5;
  32. }
  33. this.move(v2(x, y));
  34. this._w = this.node.getComponent(UITransform).contentSize.width / 2;
  35. this._h = this.node.getComponent(UITransform).contentSize.height / 2;
  36. this.node.name = type;
  37. if (type == 'xiaotou') {
  38. this.sc = 1;
  39. if(x < 0){
  40. this.node.setScale(v3(-1,1,1))
  41. }
  42. this.player.getComponent(Sprite).spriteFrame = this.xiaotou;
  43. } else {
  44. this.sc = -1;
  45. if(x < 0){
  46. this.node.setScale(v3(1,1,1))
  47. }else{
  48. this.node.setScale(v3(-1,1,1))
  49. }
  50. this.player.getComponent(Sprite).spriteFrame = this.pingmin;
  51. }
  52. }
  53. update(deltaTime: number) {
  54. if (!this._moveDirection) return;
  55. // 计算移动位置
  56. this.node.translate(v3(this._moveDirection.x * GameManager.getInstance().speed * deltaTime, this._moveDirection.y * GameManager.getInstance().speed * deltaTime, 0));
  57. if (this.node.position.x > this.node.parent.getComponent(UITransform).contentSize.width / 2 - this._w) {
  58. this._moveDirection = v2(-1, this._moveDirection.y);
  59. this.node.setScale(v3(-this.sc, 1, 1));
  60. }
  61. else if (this.node.position.x < -(this.node.parent.getComponent(UITransform).contentSize.width / 2 - this._w)) {
  62. this._moveDirection = v2(1, this._moveDirection.y);
  63. this.node.setScale(v3(this.sc, 1, 1));
  64. }
  65. if (this.node.position.y > this.node.parent.getComponent(UITransform).contentSize.height / 2 - this._h) {
  66. this._moveDirection = v2(this._moveDirection.x, -1);
  67. }
  68. else if (this.node.position.y < -(this.node.parent.getComponent(UITransform).contentSize.height / 2 - this._h)) {
  69. this._moveDirection = v2(this._moveDirection.x, 1);
  70. }
  71. }
  72. }