import { _decorator, Component, Node, Vec3, UITransform } from 'cc'; const { ccclass, property } = _decorator; @ccclass('Enemy') export class Enemy extends Component { @property speed: number = 50; @property changeDirectionTime: number = 3; private _direction: Vec3 = new Vec3(0, 0, 0); private _canvasSize: { width: number, height: number } = { width: 0, height: 0 }; private _changeDirectionTimer: number = 0; start() { // 获取画布大小 const canvas = this.node.parent.getComponent(UITransform); this._canvasSize.width = canvas.width; this._canvasSize.height = canvas.height; // 设置初始随机方向 this.setRandomDirection(); // 定时改变方向 this.schedule(this.setRandomDirection, this.changeDirectionTime); } update(dt: number) { // 移动敌人 const movement = new Vec3( this._direction.x * this.speed * dt, this._direction.y * this.speed * dt, 0 ); this.node.position = Vec3.add(new Vec3(), this.node.position, movement); // 检查边界 this.checkBoundary(); } setRandomDirection() { const angle = Math.random() * Math.PI * 2; this._direction.x = Math.cos(angle); this._direction.y = Math.sin(angle); this._direction.normalize(); } checkBoundary() { const halfWidth = this._canvasSize.width / 2 - 20; const halfHeight = this._canvasSize.height / 2 - 20; const pos = this.node.position; // 检查X轴边界 if (pos.x > halfWidth || pos.x < -halfWidth) { this._direction.x *= -1; // 调整位置,避免卡在边界 if (pos.x > halfWidth) { this.node.position = new Vec3(halfWidth, pos.y, pos.z); } else if (pos.x < -halfWidth) { this.node.position = new Vec3(-halfWidth, pos.y, pos.z); } } // 检查Y轴边界 if (pos.y > halfHeight || pos.y < -halfHeight) { this._direction.y *= -1; // 调整位置,避免卡在边界 if (pos.y > halfHeight) { this.node.position = new Vec3(pos.x, halfHeight, pos.z); } else if (pos.y < -halfHeight) { this.node.position = new Vec3(pos.x, -halfHeight, pos.z); } } } }