import { _decorator, Component, BoxCollider2D, Contact2DType, IPhysics2DContact, Node, Color, find, director } from 'cc'; import { Fruit } from './Fruit'; import { GameManager } from './GameManager'; const { ccclass, property } = _decorator; @ccclass('TopSensor') export class TopSensor extends Component { game!: GameManager; @property holdSeconds = 2.0; // 触顶持续秒数 private touching = new Map(); // node -> enterTime onLoad(){ const canvas = director.getScene().getChildByName("Canvas"); // 2. 获取 Game 节点 const gameNode = canvas.getChildByName("Game"); // 3. 获取 GameManager 脚本 this.game = gameNode.getComponent(GameManager); } onEnable() { const col = this.getComponent(BoxCollider2D)!; col.sensor = true; col.on(Contact2DType.BEGIN_CONTACT, this.onBegin, this); col.on(Contact2DType.END_CONTACT, this.onEnd, this); } onDisable() { const col = this.getComponent(BoxCollider2D)!; col.off(Contact2DType.BEGIN_CONTACT, this.onBegin, this); col.off(Contact2DType.END_CONTACT, this.onEnd, this); } private onBegin(_self: BoxCollider2D, other: any, _c: IPhysics2DContact | null) { const f = (other.node as Node).getComponent(Fruit); if (f) this.touching.set(other.node, performance.now() / 1000); } private onEnd(_self: BoxCollider2D, other: any) { this.touching.delete(other.node); } update() { if (!this.game || this.game.isGameOver) return; const now = performance.now() / 1000; for (const [node, t] of this.touching) { if (now - t >= this.holdSeconds) { this.game.gameOver(); break; } } // 可选:把状态交给 GameManager 显示红线闪烁 // this.game.setDanger(this.touching.size > 0); } }