Enemy.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { _decorator, Component, Node, Vec3, UITransform } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('Enemy')
  4. export class Enemy extends Component {
  5. @property
  6. speed: number = 50;
  7. @property
  8. changeDirectionTime: number = 3;
  9. private _direction: Vec3 = new Vec3(0, 0, 0);
  10. private _canvasSize: { width: number, height: number } = { width: 0, height: 0 };
  11. private _changeDirectionTimer: number = 0;
  12. start() {
  13. // 获取画布大小
  14. const canvas = this.node.parent.getComponent(UITransform);
  15. this._canvasSize.width = canvas.width;
  16. this._canvasSize.height = canvas.height;
  17. // 设置初始随机方向
  18. this.setRandomDirection();
  19. // 定时改变方向
  20. this.schedule(this.setRandomDirection, this.changeDirectionTime);
  21. }
  22. update(dt: number) {
  23. // 移动敌人
  24. const movement = new Vec3(
  25. this._direction.x * this.speed * dt,
  26. this._direction.y * this.speed * dt,
  27. 0
  28. );
  29. this.node.position = Vec3.add(new Vec3(), this.node.position, movement);
  30. // 检查边界
  31. this.checkBoundary();
  32. }
  33. setRandomDirection() {
  34. const angle = Math.random() * Math.PI * 2;
  35. this._direction.x = Math.cos(angle);
  36. this._direction.y = Math.sin(angle);
  37. this._direction.normalize();
  38. }
  39. checkBoundary() {
  40. const halfWidth = this._canvasSize.width / 2 - 20;
  41. const halfHeight = this._canvasSize.height / 2 - 20;
  42. const pos = this.node.position;
  43. // 检查X轴边界
  44. if (pos.x > halfWidth || pos.x < -halfWidth) {
  45. this._direction.x *= -1;
  46. // 调整位置,避免卡在边界
  47. if (pos.x > halfWidth) {
  48. this.node.position = new Vec3(halfWidth, pos.y, pos.z);
  49. } else if (pos.x < -halfWidth) {
  50. this.node.position = new Vec3(-halfWidth, pos.y, pos.z);
  51. }
  52. }
  53. // 检查Y轴边界
  54. if (pos.y > halfHeight || pos.y < -halfHeight) {
  55. this._direction.y *= -1;
  56. // 调整位置,避免卡在边界
  57. if (pos.y > halfHeight) {
  58. this.node.position = new Vec3(pos.x, halfHeight, pos.z);
  59. } else if (pos.y < -halfHeight) {
  60. this.node.position = new Vec3(pos.x, -halfHeight, pos.z);
  61. }
  62. }
  63. }
  64. }