| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- import { _decorator, Component, Node, Prefab, instantiate, Vec3, UITransform, Collider2D, Contact2DType, IPhysics2DContact } from 'cc';
- const { ccclass, property } = _decorator;
- @ccclass('GameManager')
- export class GameManager extends Component {
- @property(Prefab)
- ballPrefab: Prefab = null;
- @property(Prefab)
- bulletPrefab: Prefab = null;
- @property(Prefab)
- blockPrefab: Prefab = null;
- @property(Prefab)
- enemyPrefab: Prefab = null;
- @property(Node)
- walls: Node[] = [];
- @property
- maxEnemies: number = 5;
- private _canvasSize: { width: number, height: number } = { width: 0, height: 0 };
- private _enemies: Node[] = [];
- start() {
- // 获取画布大小
- const canvas = this.node.parent.getComponent(UITransform);
- this._canvasSize.width = canvas.width;
- this._canvasSize.height = canvas.height;
- // 创建小球
- this.createBall();
-
- // 创建方块
- this.createBlock();
-
- // 创建敌人
- this.scheduleOnce(() => {
- this.createEnemies();
- }, 1);
- }
- createBall() {
- const ball = instantiate(this.ballPrefab);
- this.node.parent.addChild(ball);
-
- // 固定位置在(80, 80)
- ball.setPosition(new Vec3(80, 80, 0));
- }
- createBlock() {
- const block = instantiate(this.blockPrefab);
- this.node.parent.addChild(block);
- block.setPosition(new Vec3(0, 0, 0));
- }
- createEnemies() {
- for (let i = 0; i < this.maxEnemies; i++) {
- this.createEnemy();
- }
- }
- createEnemy() {
- const enemy = instantiate(this.enemyPrefab);
- this.node.parent.addChild(enemy);
-
- // 随机位置(在画布边缘区域)
- const side = Math.floor(Math.random() * 4);
- let x = 0;
- let y = 0;
-
- switch (side) {
- case 0: // 上
- x = (Math.random() - 0.5) * (this._canvasSize.width - 100);
- y = this._canvasSize.height / 2 - 50;
- break;
- case 1: // 右
- x = this._canvasSize.width / 2 - 50;
- y = (Math.random() - 0.5) * (this._canvasSize.height - 100);
- break;
- case 2: // 下
- x = (Math.random() - 0.5) * (this._canvasSize.width - 100);
- y = -this._canvasSize.height / 2 + 50;
- break;
- case 3: // 左
- x = -this._canvasSize.width / 2 + 50;
- y = (Math.random() - 0.5) * (this._canvasSize.height - 100);
- break;
- }
-
- enemy.setPosition(new Vec3(x, y, 0));
- this._enemies.push(enemy);
- }
- getEnemies() {
- return this._enemies.filter(enemy => enemy.isValid);
- }
- removeEnemy(enemy: Node) {
- const index = this._enemies.indexOf(enemy);
- if (index !== -1) {
- this._enemies.splice(index, 1);
- }
-
- // 创建新敌人
- this.scheduleOnce(() => {
- this.createEnemy();
- }, 2);
- }
- }
|