import { _decorator, Component, Node, RigidBody2D, Vec2, Collider2D, Contact2DType, IPhysics2DContact } from 'cc'; import { Block } from './Block'; const { ccclass, property } = _decorator; @ccclass('Ball') export class Ball extends Component { @property initialSpeed: number = 200; private _rigidBody: RigidBody2D = null; start() { // 获取刚体组件 this._rigidBody = this.getComponent(RigidBody2D); // 延迟设置初始速度,确保物理世界已初始化 this.scheduleOnce(() => { if (this._rigidBody) { // 设置初始随机方向 const angle = Math.random() * Math.PI * 2; const directionX = Math.cos(angle); const directionY = Math.sin(angle); // 施加初始力 this._rigidBody.linearVelocity = new Vec2( directionX * this.initialSpeed, directionY * this.initialSpeed ); } }, 0.1); // 注册碰撞事件 const collider = this.getComponent(Collider2D); if (collider) { collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this); } } onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact) { // 检测是否与方块碰撞 if (otherCollider.node.name === 'Block') { // 触发方块的武器发射 const block = otherCollider.node.getComponent(Block); if (block) { block.fireBullet(); } } } }