Role.ts 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { GameManager } from "../Manager/GameManager";
  2. import {GameMain} from "./GameMain";
  3. import { _decorator, Component, Node,Collider2D, Contact2DType,IPhysics2DContact,PhysicsSystem2D, RigidBody2D, Vec2, Vec3} from 'cc';
  4. const { ccclass, property } = _decorator;
  5. @ccclass('Role')
  6. export class Role extends Component {
  7. @property(GameMain)
  8. main:GameMain = null;//获取main脚本
  9. moveSpeed=0;
  10. index:number=0;
  11. isInEnd=false;
  12. initPos=Vec3.ZERO;
  13. start () {
  14. // 注册单个碰撞体的回调函数
  15. let collider = this.getComponent(Collider2D);
  16. if (collider) {
  17. console.log('onBeginContact Role');
  18. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  19. }
  20. this.moveSpeed=(GameManager.getInstance().curLevel-1)*0.2;
  21. this.initPos=this.node.position;
  22. }
  23. onBeginContact (selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  24. // 只在两个碰撞体开始接触时被调用一次
  25. console.log('onBeginContact='+otherCollider.node.name);
  26. //
  27. if(otherCollider.tag==0)
  28. {
  29. if(this.node.name=="Role1")
  30. {
  31. this.index = 0;
  32. }
  33. else if(this.node.name=="Role2")
  34. {
  35. this.index = 1;
  36. }
  37. else if(this.node.name=="Role3")
  38. {
  39. this.index = 2;
  40. }
  41. else if(this.node.name=="Role4")
  42. {
  43. this.index = 3;
  44. }
  45. this.main.GameOver(this.index);//游戏结束
  46. this.resetStartPostion();
  47. this.main.RestoreBtn();
  48. //this.node.active = false;
  49. }
  50. else if(otherCollider.tag==1)
  51. {
  52. this.isInEnd=true;
  53. this.main.Success();
  54. this.resetStartPostion();
  55. }
  56. else if(otherCollider.tag==3){
  57. this.main.RestoreBtn();
  58. }
  59. }
  60. protected update(dt: number): void {
  61. if(!GameManager.getInstance().isStartGame)
  62. return;
  63. if(this.main.hitList[this.index]==-1){
  64. let xAxis = this.node.position.x;
  65. this.node.setPosition(xAxis+2.2+this.moveSpeed,this.node.position.y)
  66. }
  67. }
  68. resetStartPostion()
  69. {
  70. let minPosX= this.main.nodeList[0].position.x;
  71. for (let i = 1; i < 4; i++) {
  72. if(this.main.nodeList[i].position.x<minPosX)
  73. {
  74. minPosX=this.main.nodeList[i].position.x;
  75. }
  76. }
  77. if(GameManager.getInstance().curLevel<5)
  78. {
  79. this.node.setPosition(minPosX-600,this.initPos.y);
  80. }else{
  81. this.node.setPosition(minPosX-400,this.initPos.y);
  82. }
  83. console.log('resetStartPostion');
  84. }
  85. }