Ball.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { _decorator, Component, Node, RigidBody2D, Vec2, Collider2D, Contact2DType, IPhysics2DContact } from 'cc';
  2. import { Block } from './Block';
  3. const { ccclass, property } = _decorator;
  4. @ccclass('Ball')
  5. export class Ball extends Component {
  6. @property
  7. initialSpeed: number = 200;
  8. private _rigidBody: RigidBody2D = null;
  9. start() {
  10. // 获取刚体组件
  11. this._rigidBody = this.getComponent(RigidBody2D);
  12. // 延迟设置初始速度,确保物理世界已初始化
  13. this.scheduleOnce(() => {
  14. if (this._rigidBody) {
  15. // 设置初始随机方向
  16. const angle = Math.random() * Math.PI * 2;
  17. const directionX = Math.cos(angle);
  18. const directionY = Math.sin(angle);
  19. // 施加初始力
  20. this._rigidBody.linearVelocity = new Vec2(
  21. directionX * this.initialSpeed,
  22. directionY * this.initialSpeed
  23. );
  24. }
  25. }, 0.1);
  26. // 注册碰撞事件
  27. const collider = this.getComponent(Collider2D);
  28. if (collider) {
  29. collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  30. }
  31. }
  32. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact) {
  33. // 检测是否与方块碰撞
  34. if (otherCollider.node.name === 'Block') {
  35. // 触发方块的武器发射
  36. const block = otherCollider.node.getComponent(Block);
  37. if (block) {
  38. block.fireBullet();
  39. }
  40. }
  41. }
  42. }