BallController.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  1. import { _decorator, Component, Node, Vec2, Vec3, UITransform, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, Prefab, instantiate, find, CircleCollider2D } from 'cc';
  2. const { ccclass, property } = _decorator;
  3. @ccclass('BallController')
  4. export class BallController extends Component {
  5. // 球的预制体
  6. @property({
  7. type: Prefab,
  8. tooltip: '拖拽Ball预制体到这里'
  9. })
  10. public ballPrefab: Prefab = null;
  11. // 球的移动速度
  12. @property
  13. public speed: number = 50;
  14. // 子弹发射冷却时间(秒)
  15. @property
  16. public bulletCooldown: number = 0.5;
  17. // 反弹随机偏移最大角度(弧度)
  18. @property
  19. public maxReflectionRandomness: number = 0.2;
  20. // 脱离卡点的力度
  21. @property
  22. public unstuckForce: number = 10;
  23. // 脱离卡点的检测时间(秒)
  24. @property
  25. public stuckDetectionTime: number = 0.5;
  26. // 当前活动的球
  27. private activeBall: Node = null;
  28. // 球的方向向量
  29. private direction: Vec2 = new Vec2();
  30. // GameArea区域边界
  31. private gameBounds = {
  32. left: 0,
  33. right: 0,
  34. top: 0,
  35. bottom: 0
  36. };
  37. // 球的半径
  38. private radius: number = 0;
  39. // 是否已初始化
  40. private initialized: boolean = false;
  41. // 子弹冷却状态
  42. private canFireBullet: boolean = true;
  43. // 上次位置和时间,用于检测卡住
  44. private lastPosition: Vec3 = new Vec3();
  45. private stuckTimer: number = 0;
  46. private stuckCheckInterval: number = 0.1;
  47. private lastCheckTime: number = 0;
  48. // 碰撞的方块ID记录,避免重复发射
  49. private collidedBlockIds: Set<string> = new Set();
  50. // 子弹预制体
  51. @property({
  52. type: Prefab,
  53. tooltip: '拖拽子弹预制体到这里'
  54. })
  55. public bulletPrefab: Prefab = null;
  56. start() {
  57. // 计算游戏边界
  58. this.calculateGameBounds();
  59. // 检查子弹预制体是否已设置
  60. if (this.bulletPrefab) {
  61. console.log('子弹预制体已设置:', this.bulletPrefab.name);
  62. } else {
  63. console.error('子弹预制体未设置!请在编辑器中设置bulletPrefab属性');
  64. }
  65. }
  66. // 计算游戏边界(使用GameArea节点)
  67. calculateGameBounds() {
  68. // 获取GameArea节点
  69. const gameArea = find('Canvas/GameLevelUI/GameArea');
  70. if (!gameArea) {
  71. console.error('找不到GameArea节点');
  72. return;
  73. }
  74. const gameAreaUI = gameArea.getComponent(UITransform);
  75. if (!gameAreaUI) {
  76. console.error('GameArea节点没有UITransform组件');
  77. return;
  78. }
  79. // 获取GameArea的尺寸
  80. const areaWidth = gameAreaUI.width;
  81. const areaHeight = gameAreaUI.height;
  82. // 获取GameArea的世界坐标位置
  83. const worldPos = gameArea.worldPosition;
  84. // 计算GameArea的世界坐标边界
  85. this.gameBounds.left = worldPos.x - areaWidth / 2;
  86. this.gameBounds.right = worldPos.x + areaWidth / 2;
  87. this.gameBounds.bottom = worldPos.y - areaHeight / 2;
  88. this.gameBounds.top = worldPos.y + areaHeight / 2;
  89. console.log('GameArea Bounds:', this.gameBounds);
  90. }
  91. // 创建小球
  92. createBall() {
  93. if (!this.ballPrefab) {
  94. console.error('未设置Ball预制体');
  95. return;
  96. }
  97. // 如果已经有活动的球,先销毁它
  98. if (this.activeBall && this.activeBall.isValid) {
  99. this.activeBall.destroy();
  100. }
  101. // 实例化小球
  102. this.activeBall = instantiate(this.ballPrefab);
  103. // 将小球添加到GameArea中
  104. const gameArea = find('Canvas/GameLevelUI/GameArea');
  105. if (gameArea) {
  106. gameArea.addChild(this.activeBall);
  107. } else {
  108. this.node.addChild(this.activeBall);
  109. }
  110. // 随机位置小球
  111. this.positionBallRandomly();
  112. // 设置球的半径
  113. const transform = this.activeBall.getComponent(UITransform);
  114. if (transform) {
  115. this.radius = transform.width / 2;
  116. console.log('小球半径设置为:', this.radius);
  117. } else {
  118. this.radius = 25; // 默认半径
  119. console.warn('无法获取小球UITransform组件,使用默认半径:', this.radius);
  120. }
  121. // 确保有碰撞组件
  122. this.setupCollider();
  123. // 初始化方向
  124. this.initializeDirection();
  125. this.initialized = true;
  126. console.log('小球创建完成:', {
  127. position: this.activeBall.position,
  128. radius: this.radius,
  129. initialized: this.initialized
  130. });
  131. }
  132. // 随机位置小球
  133. positionBallRandomly() {
  134. if (!this.activeBall) return;
  135. const transform = this.activeBall.getComponent(UITransform);
  136. const ballRadius = transform ? transform.width / 2 : 25;
  137. // 计算可生成的范围(考虑小球半径,避免生成在边缘)
  138. const minX = this.gameBounds.left + ballRadius + 20; // 额外偏移,避免生成在边缘
  139. const maxX = this.gameBounds.right - ballRadius - 20;
  140. const minY = this.gameBounds.bottom + ballRadius + 20;
  141. const maxY = this.gameBounds.top - ballRadius - 20;
  142. // 获取GameArea节点
  143. const gameArea = find('Canvas/GameLevelUI/GameArea');
  144. if (!gameArea) {
  145. console.error('找不到GameArea节点');
  146. return;
  147. }
  148. // 查找GridContainer节点,它包含所有放置的方块
  149. const gridContainer = gameArea.getChildByName('GridContainer');
  150. if (!gridContainer) {
  151. console.log('找不到GridContainer节点,使用默认随机位置');
  152. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  153. return;
  154. }
  155. // 获取所有已放置的方块
  156. const placedBlocks = [];
  157. for (let i = 0; i < gridContainer.children.length; i++) {
  158. const cell = gridContainer.children[i];
  159. // 检查单元格是否有子节点(放置的方块)
  160. if (cell.children.length > 0) {
  161. placedBlocks.push(cell);
  162. }
  163. }
  164. console.log(`找到 ${placedBlocks.length} 个已放置的方块`);
  165. // 如果没有方块,使用默认随机位置
  166. if (placedBlocks.length === 0) {
  167. this.setRandomPositionDefault(minX, maxX, minY, maxY);
  168. return;
  169. }
  170. // 尝试找到一个不与任何方块重叠的位置
  171. let validPosition = false;
  172. let attempts = 0;
  173. const maxAttempts = 50; // 最大尝试次数
  174. let randomX, randomY;
  175. while (!validPosition && attempts < maxAttempts) {
  176. // 随机生成位置
  177. randomX = Math.random() * (maxX - minX) + minX;
  178. randomY = Math.random() * (maxY - minY) + minY;
  179. // 检查是否与任何方块重叠
  180. let overlapping = false;
  181. for (const block of placedBlocks) {
  182. // 获取方块的世界坐标
  183. const blockWorldPos = block.worldPosition;
  184. // 计算小球与方块的距离
  185. const distance = Math.sqrt(
  186. Math.pow(randomX - blockWorldPos.x, 2) +
  187. Math.pow(randomY - blockWorldPos.y, 2)
  188. );
  189. // 获取方块的尺寸
  190. const blockTransform = block.getComponent(UITransform);
  191. const blockSize = blockTransform ?
  192. Math.max(blockTransform.width, blockTransform.height) / 2 : 50;
  193. // 如果距离小于小球半径+方块尺寸的一半+安全距离,认为重叠
  194. const safeDistance = 20; // 额外安全距离
  195. if (distance < ballRadius + blockSize + safeDistance) {
  196. overlapping = true;
  197. break;
  198. }
  199. }
  200. // 如果没有重叠,找到了有效位置
  201. if (!overlapping) {
  202. validPosition = true;
  203. }
  204. attempts++;
  205. }
  206. // 如果找不到有效位置,使用默认位置(游戏区域底部中心)
  207. if (!validPosition) {
  208. console.log(`尝试 ${maxAttempts} 次后未找到有效位置,使用默认位置`);
  209. randomX = (this.gameBounds.left + this.gameBounds.right) / 2;
  210. randomY = this.gameBounds.bottom + ballRadius + 50; // 底部上方50单位
  211. }
  212. // 将世界坐标转换为相对于GameArea的本地坐标
  213. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  214. this.activeBall.position = localPos;
  215. console.log('小球位置已设置:', {
  216. worldX: randomX,
  217. worldY: randomY,
  218. localX: localPos.x,
  219. localY: localPos.y,
  220. overlapsWithBlock: !validPosition
  221. });
  222. }
  223. // 设置默认随机位置
  224. setRandomPositionDefault(minX, maxX, minY, maxY) {
  225. // 随机生成位置
  226. const randomX = Math.random() * (maxX - minX) + minX;
  227. const randomY = Math.random() * (maxY - minY) + minY;
  228. // 将世界坐标转换为相对于GameArea的本地坐标
  229. const gameArea = find('Canvas/GameLevelUI/GameArea');
  230. if (gameArea) {
  231. const localPos = gameArea.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(randomX, randomY, 0));
  232. this.activeBall.position = localPos;
  233. } else {
  234. // 直接设置位置(不太准确,但作为后备)
  235. this.activeBall.position = new Vec3(randomX - this.gameBounds.left, randomY - this.gameBounds.bottom, 0);
  236. }
  237. console.log('使用默认随机位置设置小球:', {
  238. worldX: randomX,
  239. worldY: randomY
  240. });
  241. }
  242. // 设置碰撞组件
  243. setupCollider() {
  244. if (!this.activeBall) return;
  245. // 确保小球有刚体组件
  246. let rigidBody = this.activeBall.getComponent(RigidBody2D);
  247. if (!rigidBody) {
  248. rigidBody = this.activeBall.addComponent(RigidBody2D);
  249. rigidBody.type = 2; // Dynamic
  250. rigidBody.gravityScale = 0; // 不受重力影响
  251. rigidBody.enabledContactListener = true; // 启用碰撞监听
  252. rigidBody.fixedRotation = true; // 固定旋转
  253. rigidBody.allowSleep = false; // 不允许休眠
  254. rigidBody.linearDamping = 0; // 无阻尼
  255. rigidBody.angularDamping = 0; // 无角阻尼
  256. } else {
  257. // 确保已有的刚体组件设置正确
  258. rigidBody.enabledContactListener = true;
  259. rigidBody.gravityScale = 0;
  260. }
  261. // 确保小球有碰撞组件
  262. let collider = this.activeBall.getComponent(CircleCollider2D);
  263. if (!collider) {
  264. collider = this.activeBall.addComponent(CircleCollider2D);
  265. collider.radius = this.radius || 25; // 使用已计算的半径或默认值
  266. collider.tag = 1; // 小球标签
  267. collider.group = 1; // 碰撞组
  268. collider.sensor = false; // 非传感器(实际碰撞)
  269. collider.friction = 0; // 无摩擦
  270. collider.restitution = 1; // 完全弹性碰撞
  271. } else {
  272. // 确保已有的碰撞组件设置正确
  273. collider.sensor = false;
  274. collider.restitution = 1;
  275. }
  276. console.log('小球碰撞组件设置完成:', {
  277. hasRigidBody: !!rigidBody,
  278. hasCollider: !!collider,
  279. radius: collider ? collider.radius : 'unknown'
  280. });
  281. // 移除可能存在的事件监听
  282. this.activeBall.off(Contact2DType.BEGIN_CONTACT);
  283. this.activeBall.off(Contact2DType.END_CONTACT);
  284. this.activeBall.off(Contact2DType.PRE_SOLVE);
  285. this.activeBall.off(Contact2DType.POST_SOLVE);
  286. // 注册所有类型的碰撞事件
  287. this.activeBall.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
  288. this.activeBall.on(Contact2DType.END_CONTACT, this.onEndContact, this);
  289. this.activeBall.on(Contact2DType.PRE_SOLVE, this.onPreSolve, this);
  290. this.activeBall.on(Contact2DType.POST_SOLVE, this.onPostSolve, this);
  291. console.log('已注册所有碰撞事件监听器');
  292. }
  293. // 碰撞回调中,只需要更新方向向量,物理引擎会处理实际的反弹
  294. onBeginContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  295. // 获取碰撞点和法线
  296. if (!contact) {
  297. console.warn('碰撞事件没有contact对象');
  298. return;
  299. }
  300. // 记录碰撞对象信息
  301. console.log('碰撞发生:', {
  302. selfName: selfCollider.node.name,
  303. otherName: otherCollider.node.name,
  304. otherPath: this.getNodePath(otherCollider.node)
  305. });
  306. // Debug: 检查节点名称是否包含Block
  307. console.log(`检查节点名称: "${otherCollider.node.name}",是否包含'Block': ${otherCollider.node.name.includes('Block')}`);
  308. // 获取碰撞点的世界坐标
  309. const worldManifold = contact.getWorldManifold();
  310. if (!worldManifold) {
  311. console.warn('无法获取worldManifold');
  312. return;
  313. }
  314. // 获取碰撞法线
  315. const normal = worldManifold.normal;
  316. console.log('碰撞法线:', normal);
  317. // 检查是否碰到墙体
  318. const nodeName = otherCollider.node.name;
  319. const nodePath = this.getNodePath(otherCollider.node);
  320. const nodeParent = otherCollider.node.parent ? otherCollider.node.parent.name : 'unknown';
  321. console.log(`检查墙体碰撞: ${nodeName}, 路径: ${nodePath}, 父节点: ${nodeParent}`);
  322. // 使用多种方式检测墙体碰撞
  323. const isWall =
  324. nodeName === 'TopFence' ||
  325. nodeName === 'BottomFence' ||
  326. nodeName === 'JiguangL' ||
  327. nodeName === 'JiguangR' ||
  328. nodeName.includes('Fence') ||
  329. nodeName.includes('Jiguang') ||
  330. nodePath.includes('GameArea/TopFence') ||
  331. nodePath.includes('GameArea/BottomFence') ||
  332. nodePath.includes('GameArea/JiguangL') ||
  333. nodePath.includes('GameArea/JiguangR');
  334. if (isWall) {
  335. console.log(`球碰到了墙体 ${nodeName},进行反弹,路径: ${nodePath}`);
  336. // 更新方向向量
  337. this.direction = this.calculateReflection(this.direction, normal);
  338. // 确保球有刚体组件
  339. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  340. if (rigidBody) {
  341. // 立即更新速度方向,确保反弹效果
  342. rigidBody.linearVelocity = new Vec2(
  343. this.direction.x * this.speed,
  344. this.direction.y * this.speed
  345. );
  346. console.log('更新后的速度:', rigidBody.linearVelocity);
  347. // 强制设置位置,避免卡在墙内
  348. const ballPos = this.activeBall.worldPosition;
  349. const ballRadius = this.radius;
  350. // 根据碰撞法线调整位置
  351. if (Math.abs(normal.y) > Math.abs(normal.x)) {
  352. // 上下墙体碰撞
  353. if (normal.y > 0) {
  354. // 下墙
  355. this.activeBall.setWorldPosition(new Vec3(
  356. ballPos.x,
  357. ballPos.y + ballRadius * 0.5,
  358. ballPos.z
  359. ));
  360. } else {
  361. // 上墙
  362. this.activeBall.setWorldPosition(new Vec3(
  363. ballPos.x,
  364. ballPos.y - ballRadius * 0.5,
  365. ballPos.z
  366. ));
  367. }
  368. } else {
  369. // 左右墙体碰撞
  370. if (normal.x > 0) {
  371. // 左墙
  372. this.activeBall.setWorldPosition(new Vec3(
  373. ballPos.x + ballRadius * 0.5,
  374. ballPos.y,
  375. ballPos.z
  376. ));
  377. } else {
  378. // 右墙
  379. this.activeBall.setWorldPosition(new Vec3(
  380. ballPos.x - ballRadius * 0.5,
  381. ballPos.y,
  382. ballPos.z
  383. ));
  384. }
  385. }
  386. }
  387. }
  388. // 如果碰撞的是方块,发射子弹
  389. // 修改检测逻辑,使用更宽松的条件
  390. const isBlock =
  391. nodeName.includes('Block') ||
  392. nodePath.includes('Block') ||
  393. (otherCollider.node.getChildByName('Weapon') !== null);
  394. if (isBlock) {
  395. console.log(`检测到方块碰撞: ${nodeName}, 路径: ${nodePath}`);
  396. // 检查冷却状态和是否已经对这个方块发射过子弹
  397. const blockId = otherCollider.node.uuid;
  398. if (this.canFireBullet && !this.collidedBlockIds.has(blockId)) {
  399. this.fireBullet(otherCollider.node);
  400. } else {
  401. console.log('子弹冷却中或已对此方块发射过子弹');
  402. }
  403. }
  404. }
  405. // 碰撞结束事件
  406. onEndContact(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  407. console.log('碰撞结束:', otherCollider.node.name);
  408. }
  409. // 碰撞预处理事件
  410. onPreSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  411. console.log('碰撞预处理:', otherCollider.node.name);
  412. }
  413. // 碰撞后处理事件
  414. onPostSolve(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null) {
  415. console.log('碰撞后处理:', otherCollider.node.name);
  416. // 检查是否碰到墙体
  417. const nodeName = otherCollider.node.name;
  418. if (nodeName === 'TopFence' || nodeName === 'BottomFence' ||
  419. nodeName === 'JiguangL' || nodeName === 'JiguangR' ||
  420. nodeName.includes('Fence') || nodeName.includes('Jiguang')) {
  421. console.log(`球碰到了墙体 ${nodeName},处理反弹`);
  422. // 获取碰撞点和法线
  423. if (!contact) return;
  424. const worldManifold = contact.getWorldManifold();
  425. if (!worldManifold) return;
  426. // 获取碰撞法线
  427. const normal = worldManifold.normal;
  428. // 更新方向向量
  429. this.direction = this.calculateReflection(this.direction, normal);
  430. // 确保球有刚体组件
  431. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  432. if (rigidBody) {
  433. // 立即更新速度方向,确保反弹效果
  434. rigidBody.linearVelocity = new Vec2(
  435. this.direction.x * this.speed,
  436. this.direction.y * this.speed
  437. );
  438. }
  439. }
  440. }
  441. // 计算反射向量
  442. calculateReflection(direction: Vec2, normal: Vec2): Vec2 {
  443. // 使用反射公式: R = V - 2(V·N)N
  444. const dot = direction.x * normal.x + direction.y * normal.y;
  445. const reflection = new Vec2(
  446. direction.x - 2 * dot * normal.x,
  447. direction.y - 2 * dot * normal.y
  448. );
  449. reflection.normalize();
  450. // 添加一些随机性,避免重复的反弹路径
  451. const randomAngle = (Math.random() - 0.5) * this.maxReflectionRandomness; // 随机角度
  452. const cos = Math.cos(randomAngle);
  453. const sin = Math.sin(randomAngle);
  454. // 应用随机旋转
  455. const randomizedReflection = new Vec2(
  456. reflection.x * cos - reflection.y * sin,
  457. reflection.x * sin + reflection.y * cos
  458. );
  459. // 确保反射方向不会太接近水平或垂直方向
  460. // 这有助于避免球在水平或垂直方向上来回反弹
  461. const minAngleFromAxis = 0.1; // 约5.7度
  462. // 检查是否接近水平方向
  463. if (Math.abs(randomizedReflection.y) < minAngleFromAxis) {
  464. // 调整y分量,使其远离水平方向
  465. const sign = randomizedReflection.y >= 0 ? 1 : -1;
  466. randomizedReflection.y = sign * (minAngleFromAxis + Math.random() * 0.1);
  467. // 重新归一化
  468. randomizedReflection.normalize();
  469. }
  470. // 检查是否接近垂直方向
  471. if (Math.abs(randomizedReflection.x) < minAngleFromAxis) {
  472. // 调整x分量,使其远离垂直方向
  473. const sign = randomizedReflection.x >= 0 ? 1 : -1;
  474. randomizedReflection.x = sign * (minAngleFromAxis + Math.random() * 0.1);
  475. // 重新归一化
  476. randomizedReflection.normalize();
  477. }
  478. randomizedReflection.normalize();
  479. console.log('反射方向:', {
  480. original: direction,
  481. normal: normal,
  482. reflection: reflection,
  483. randomized: randomizedReflection
  484. });
  485. return randomizedReflection;
  486. }
  487. // 发射子弹
  488. fireBullet(blockNode: Node) {
  489. console.log('发射子弹!击中方块:', blockNode.name);
  490. // 检查冷却状态
  491. if (!this.canFireBullet) {
  492. console.log('子弹冷却中,无法发射');
  493. return;
  494. }
  495. // 检查是否已经对这个方块发射过子弹
  496. const blockId = blockNode.uuid;
  497. if (this.collidedBlockIds.has(blockId)) {
  498. console.log('已经对此方块发射过子弹');
  499. return;
  500. }
  501. // 记录此方块ID
  502. this.collidedBlockIds.add(blockId);
  503. // 设置冷却
  504. this.canFireBullet = false;
  505. this.scheduleOnce(() => {
  506. this.canFireBullet = true;
  507. // 清理碰撞记录
  508. this.collidedBlockIds.clear();
  509. }, this.bulletCooldown);
  510. // 检查是否有子弹预制体
  511. if (!this.bulletPrefab) {
  512. console.error('未设置子弹预制体');
  513. return;
  514. } else {
  515. console.log('子弹预制体已设置:', this.bulletPrefab.name);
  516. }
  517. // 查找Weapon节点 - 递归查找,因为Weapon可能在B1子节点下
  518. let weaponNode = this.findWeaponNode(blockNode);
  519. if (!weaponNode) {
  520. console.warn(`方块 ${blockNode.name} 没有找到Weapon子节点,创建一个`);
  521. // 如果没有找到Weapon节点,在B1节点下创建一个
  522. const b1Node = blockNode.getChildByName('B1');
  523. if (b1Node) {
  524. weaponNode = new Node('Weapon');
  525. // 确保Weapon节点有UITransform组件
  526. if (!weaponNode.getComponent(UITransform)) {
  527. weaponNode.addComponent(UITransform);
  528. }
  529. // 将Weapon添加到B1节点中
  530. b1Node.addChild(weaponNode);
  531. // 放置在B1中心
  532. weaponNode.position = new Vec3(0, 0, 0);
  533. } else {
  534. // 如果连B1节点都没有,直接添加到方块根节点
  535. weaponNode = new Node('Weapon');
  536. // 确保Weapon节点有UITransform组件
  537. if (!weaponNode.getComponent(UITransform)) {
  538. weaponNode.addComponent(UITransform);
  539. }
  540. // 将Weapon添加到方块中
  541. blockNode.addChild(weaponNode);
  542. // 放置在方块中心
  543. weaponNode.position = new Vec3(0, 0, 0);
  544. }
  545. } else {
  546. console.log(`找到方块 ${blockNode.name} 的Weapon子节点:`, weaponNode.name);
  547. }
  548. // 实例化子弹
  549. const bullet = instantiate(this.bulletPrefab);
  550. // 将子弹添加到GameArea中
  551. const gameArea = find('Canvas/GameLevelUI/GameArea');
  552. if (gameArea) {
  553. gameArea.addChild(bullet);
  554. // 设置子弹初始位置为Weapon节点的位置
  555. const weaponWorldPos = weaponNode.worldPosition;
  556. bullet.worldPosition = weaponWorldPos;
  557. // 子弹已经有BulletController组件,不需要再添加
  558. // 让子弹自己找到最近的敌人并攻击
  559. console.log('子弹已创建,将自动寻找并攻击最近的敌人');
  560. }
  561. }
  562. // 递归查找Weapon节点
  563. private findWeaponNode(node: Node): Node | null {
  564. // 先检查当前节点是否有Weapon子节点
  565. const weaponNode = node.getChildByName('Weapon');
  566. if (weaponNode) {
  567. return weaponNode;
  568. }
  569. // 如果没有,递归检查所有子节点
  570. for (let i = 0; i < node.children.length; i++) {
  571. const child = node.children[i];
  572. const foundWeapon = this.findWeaponNode(child);
  573. if (foundWeapon) {
  574. return foundWeapon;
  575. }
  576. }
  577. // 如果都没找到,返回null
  578. return null;
  579. }
  580. // 获取节点的完整路径
  581. private getNodePath(node: Node): string {
  582. let path = node.name;
  583. let current = node;
  584. while (current.parent) {
  585. current = current.parent;
  586. path = current.name + '/' + path;
  587. }
  588. return path;
  589. }
  590. update(dt: number) {
  591. // 如果使用物理引擎,不要手动更新位置
  592. if (!this.initialized || !this.activeBall || !this.activeBall.isValid) return;
  593. // 使用刚体组件控制小球移动,而不是直接设置位置
  594. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  595. if (rigidBody) {
  596. // 检查速度是否过小或为零,如果是则恢复速度
  597. const currentVelocity = rigidBody.linearVelocity;
  598. const speed = Math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y);
  599. if (speed < 1.0) {
  600. console.log('检测到速度过小,恢复速度:', speed);
  601. // 如果速度太小,恢复到正常速度
  602. this.direction.normalize();
  603. rigidBody.linearVelocity = new Vec2(
  604. this.direction.x * this.speed,
  605. this.direction.y * this.speed
  606. );
  607. }
  608. // 确保方向向量与实际速度方向一致
  609. if (speed > 1.0) {
  610. this.direction.x = currentVelocity.x / speed;
  611. this.direction.y = currentVelocity.y / speed;
  612. }
  613. // 手动检测墙体碰撞
  614. this.checkWallCollisions();
  615. }
  616. // 手动检测方块碰撞
  617. this.checkBlockCollisions();
  618. }
  619. // 手动检测墙体碰撞
  620. checkWallCollisions() {
  621. if (!this.activeBall || !this.activeBall.isValid) return;
  622. // 获取小球的世界坐标
  623. const ballPos = this.activeBall.worldPosition;
  624. const ballRadius = this.radius;
  625. // 检查是否碰到上下左右边界
  626. let collided = false;
  627. let normal = new Vec2(0, 0);
  628. // 上边界碰撞
  629. if (ballPos.y + ballRadius >= this.gameBounds.top) {
  630. normal.y = -1;
  631. collided = true;
  632. console.log('手动检测到上边界碰撞');
  633. // 修正位置,避免卡在边界
  634. this.activeBall.setWorldPosition(new Vec3(
  635. ballPos.x,
  636. this.gameBounds.top - ballRadius - 0.1,
  637. ballPos.z
  638. ));
  639. }
  640. // 下边界碰撞
  641. else if (ballPos.y - ballRadius <= this.gameBounds.bottom) {
  642. normal.y = 1;
  643. collided = true;
  644. console.log('手动检测到下边界碰撞');
  645. // 修正位置,避免卡在边界
  646. this.activeBall.setWorldPosition(new Vec3(
  647. ballPos.x,
  648. this.gameBounds.bottom + ballRadius + 0.1,
  649. ballPos.z
  650. ));
  651. }
  652. // 左边界碰撞
  653. if (ballPos.x - ballRadius <= this.gameBounds.left) {
  654. normal.x = 1;
  655. collided = true;
  656. console.log('手动检测到左边界碰撞');
  657. // 修正位置,避免卡在边界
  658. this.activeBall.setWorldPosition(new Vec3(
  659. this.gameBounds.left + ballRadius + 0.1,
  660. ballPos.y,
  661. ballPos.z
  662. ));
  663. }
  664. // 右边界碰撞
  665. else if (ballPos.x + ballRadius >= this.gameBounds.right) {
  666. normal.x = -1;
  667. collided = true;
  668. console.log('手动检测到右边界碰撞');
  669. // 修正位置,避免卡在边界
  670. this.activeBall.setWorldPosition(new Vec3(
  671. this.gameBounds.right - ballRadius - 0.1,
  672. ballPos.y,
  673. ballPos.z
  674. ));
  675. }
  676. // 如果碰到边界,计算反弹
  677. if (collided) {
  678. // 标准化法向量
  679. if (normal.x !== 0 || normal.y !== 0) {
  680. normal.normalize();
  681. }
  682. // 计算反射方向
  683. this.direction = this.calculateReflection(this.direction, normal);
  684. // 更新速度
  685. const rigidBody = this.activeBall.getComponent(RigidBody2D);
  686. if (rigidBody) {
  687. // 立即更新速度方向,确保反弹效果
  688. rigidBody.linearVelocity = new Vec2(
  689. this.direction.x * this.speed,
  690. this.direction.y * this.speed
  691. );
  692. console.log('手动更新速度方向:', this.direction);
  693. }
  694. }
  695. }
  696. // 手动检测方块碰撞
  697. checkBlockCollisions() {
  698. if (!this.activeBall) return;
  699. // 获取场景中所有方块
  700. const placedBlocks = find('Canvas/PlacedBlocks');
  701. if (!placedBlocks) return;
  702. const ballPos = this.activeBall.worldPosition;
  703. const ballRadius = this.radius;
  704. // 检查与每个方块的碰撞
  705. for (let i = 0; i < placedBlocks.children.length; i++) {
  706. const block = placedBlocks.children[i];
  707. if (!block.name.includes('Block')) continue;
  708. // 简单距离检测(可以根据实际情况优化)
  709. const blockPos = block.worldPosition;
  710. const distance = Vec3.distance(ballPos, blockPos);
  711. // 如果距离小于某个阈值,认为发生碰撞
  712. if (distance < ballRadius + 50) { // 50是一个估计值,根据方块大小调整
  713. console.log('手动检测到与方块碰撞:', block.name);
  714. this.fireBullet(block);
  715. break;
  716. }
  717. }
  718. }
  719. // 初始化方向
  720. initializeDirection() {
  721. // 随机初始方向
  722. const angle = Math.random() * Math.PI * 2; // 0-2π之间的随机角度
  723. this.direction.x = Math.cos(angle);
  724. this.direction.y = Math.sin(angle);
  725. this.direction.normalize();
  726. console.log('Ball initialized with direction:', this.direction);
  727. }
  728. // 初始化球的参数 - 公开方法,供GameManager调用
  729. initialize() {
  730. this.calculateGameBounds();
  731. this.createBall();
  732. }
  733. }